求逆序对

原题洛谷上有,它bb了一大堆背景就为了让你求个逆序对。
所以题我就不复制了,我只放代码就好了
 

#include
#include
#include
#include
using namespace std;
int n;
long long ans = 0;
int a[500003],b[500003];
void merge(int l,int mid ,int r)
{
	int i = l,k = l,j = mid + 1;
	while(i <= mid && j <= r)
	{
		if(a[i] <= a[j])b[k++] = a[i++];
		else b[k++] = a[j++],ans += mid - i + 1;
	}
	while(i <= mid)b[k++] = a[i++];
	while(j <= r)b[k++] = a[j++];
	for(int i = l;i <= r;i++)a[i] = b[i];
}
void mergesort(int l,int r)
{
	if(l < r)
	{
		int mid = (l + r)/2;
		mergesort(l,mid);
		mergesort(mid + 1,r);
		merge(l,mid,r);
	}
}
int main()
{
	scanf("%d",&n);
	for(int i = 1;i <= n;i++)scanf("%d",&a[i]);
	mergesort(1,n); 
	printf("%lld",ans);
	return 0;
}

还有轰总真的帅

你可能感兴趣的:(分治)