POJ2299: Ultra-QuickSort-合并排序解决逆序数问题

 1 #include<iostream>
 2 #include<malloc.h>
 3 using namespace std;
 4 long long ans;
 5 void merge(int *a,int le,int mid,int rt){
 6     int *sort_data=(int *)malloc(sizeof(int)*(rt-le+1));
 7     if(!sort_data) return;
 8     int i=le,j=mid+1,pt=0;
 9     while(i<=mid&&j<=rt){
10         if(a[i]<=a[j]){
11             sort_data[pt++]=a[i++];
12         }
13         else{//exist swap action
14             sort_data[pt++]=a[j++];
15             /*
16                 once we swap the postion of both the a[i] and a[j],
17                 we do change the positon of a[i+1......mid]
18                 so as a result, we do change the postion of a[i,i+1,....mid].
19             */
20             ans+=mid-i+1;
21         }
22     }
23     while(i<=mid){
24         sort_data[pt++]=a[i++];
25     }
26     while(j<=rt){
27         sort_data[pt++]=a[j++];
28     }
29     int p;
30     for(int i=le,p=0;i<=rt;i++,p++){
31         a[i]=sort_data[p];
32     }
33 }
34 void mergeSort(int a[],int st,int ed){
35     if(st<ed){
36         int mid=(st+ed)/2;
37         mergeSort(a,st,mid);
38         mergeSort(a,mid+1,ed);
39         merge(a,st,mid,ed);
40     }
41 }
42 int main(){
43     int n,num[500010];
44     while(scanf("%d",&n),n){
45         ans=0;
46         for(int i=0;i<n;i++){
47             scanf("%d",&num[i]);
48         } 
49         mergeSort(num,0,n-1);
50         printf("%I64d\n",ans);
51     }
52     return 0;
53 }
View Code

 

posted @ 2014-12-31 17:19  流白  阅读(152)  评论(0编辑  收藏  举报