逆序对(POJ2299 Ultra-QuickSort)
1 #include<bits/stdc++.h> 2 using namespace std; 3 int n; 4 long long a[500005],b[500005],ans;//a为待排序数组,b为临时数组,ans为逆序对数 5 void mergesort(int l,int r)//l为左边界,r为右边界 6 { 7 if(l==r) return; 8 int mid=(l+r)>>1; 9 mergesort(l,mid); 10 mergesort(mid+1,r); 11 int i=l,j=mid+1,k=l; 12 while(i<=mid&&j<=r) 13 { 14 if(a[i]<=a[j]) b[k++]=a[i++]; //注意等号 若a[i]==a[j] 则不构成逆序对 15 else b[k++]=a[j++],ans+=mid-i+1;//求逆序对 16 } 17 while(i<=mid) b[k++]=a[i++]; 18 while(j<=r) b[k++]=a[j++]; 19 for(int i=l;i<=r;i++) a[i]=b[i]; 20 } 21 int main() 22 { 23 scanf("%d",&n); 24 while(n) 25 { 26 ans=0; 27 memset(a,0,sizeof(a)); 28 memset(b,0,sizeof(b)); 29 for(int i=1;i<=n;i++) scanf("%d",&a[i]); 30 mergesort(1,n); 31 printf("%lld\n",ans); 32 scanf("%d",&n); 33 } 34 return 0; 35 }