归并排序(求逆序数对)

#include <iostream>
#include <cstdio>
using namespace std;

int A[1000005];
long long int ans=0;

void merge(int l,int r)
{
  int mid=(l+r)/2;
  int left[mid-l+1];
  int right[r-mid];
  int i;
  int lcount=0,rcount=0;
  for (i=l;i<=mid;i++)
  	left[lcount++]=A[i];
  for (i=mid+1;i<=r;i++)
  	right[rcount++]=A[i];

  int lp=0,rp=0;
  int Acount=0;
  while (lp!=lcount || rp!=rcount)
  {
  	if (rp==rcount || (left[lp]<=right[rp] && lp!=lcount))
  	{
  		A[l+Acount]=left[lp];
  		Acount++;
  		lp++;
  	}
  	else
  	{
  		A[l+Acount]=right[rp];
  		Acount++;
  		rp++;
  		ans+=(lcount-lp);
  	}
  }
}

void mergesort(int l,int r)
{
  int mid=(l+r)/2;
  if (l<r)
  {
    mergesort(l,mid);
    mergesort(mid+1,r);
    merge(l,r);
  }
}

int main()
{
	int n;
	scanf("%d",&n);
	int i;
	for (i=0;i<=n-1;i++)
		scanf("%d",&A[i]);
	mergesort(0,n-1);
	printf("%lld\n",ans);
  return 0;
}

你可能感兴趣的:(归并排序(求逆序数对))