xmu 1328.不高兴的bobo

#include <stdio.h>
#include<stdlib.h>
#define MAXNUM 1000002

int arr[MAXNUM]={0};
int arr_temp[MAXNUM];
long long ans;
//归并排序
void merge(int left,int middle,int right)
{
	int i,j,k;
	i=left;j=middle+1;k=0;
	while (i<=middle && j<=right)
	{
		if(arr[j]<arr[i])
		{
			arr_temp[k++]=arr[j++];
			ans+=(middle-i+1);
		}
		else
		{
			arr_temp[k++]=arr[i++];
		}
	}
	while(i<=middle)
		arr_temp[k++]=arr[i++];
	while(j<=right)
		arr_temp[k++]=arr[j++];
	for (i=0;i<k;i++)
	{
		arr[left+i]=arr_temp[i];
	}

}

void merge_sort(int left,int right)
{
	if(left<right)
	{
		int middle=(left+right)/2;
		merge_sort(left,middle);
		merge_sort(middle+1,right);
		merge(left,middle,right);
	}
}
int main()
{
	int n,i;
	scanf("%d",&n);
	for(i=0;i<n;i++)
		scanf("%d",&arr[i]);
	ans=0;
	merge_sort(0,n-1);
	printf("%lld\n",ans);
	return 0;
}

你可能感兴趣的:(xmu 1328.不高兴的bobo)