标签:
Description
Input
Output
Sample Input
Sample Output
1 #include <iostream> 2 using namespace std; 3 4 const int N=1000005; 5 int num[N]; 6 int temp[N]; 7 long long ans; 8 9 void merge(int left,int mid,int right) 10 { 11 int i=left,j=mid+1; 12 int p=0; 13 while (i<=mid&&j<=right) 14 { 15 if (num[i]<=num[j]) temp[p++]=num[i++]; 16 else 17 { 18 ans+=mid-i+1; //就是num[j]到num[i]要经过几次调换 19 temp[p++]=num[j++]; 20 } 21 } 22 while (i<=mid) temp[p++]=num[i++]; 23 while (j<=right) temp[p++]=num[j++]; 24 j=left; 25 for (i=0;i<p;i++) 26 num[j++]=temp[i]; 27 } 28 29 void mergesort(int left,int right) 30 { 31 int mid; 32 if (left<right) 33 { 34 mid=(left+right)/2; 35 mergesort(left,mid); //左边还可以分的话,归并左边 36 mergesort(mid+1,right); //右边可以分的话,归并右边 37 merge(left,mid,right); //合并两个已经并好的 38 } 39 } 40 41 int main() 42 { 43 int n,i; 44 while (scanf("%d",&n)!=EOF) 45 { 46 ans=0; 47 for (i=0;i<n;i++) 48 scanf("%d",&num[i]); 49 mergesort(0,n-1); 50 printf("%lld\n",ans); 51 } 52 return 0; 53 }
标签:
原文地址:http://www.cnblogs.com/haoabcd2010/p/5690997.html