1、题目链接
http://acm.hrbust.edu.cn/vj/index.php?c=problem-problem&id=166400
//归并排序求解逆序对 #include<iostream> #include<stdio.h> #include<math.h> #include<algorithm> #include<stack> #include<queue> #include<string.h> typedef long long int ll; using namespace std; ll n,sum; ll a[500005],temp[500005]; void Merge(ll a[],ll l,ll mid,ll r){ ll i=l,j=mid+1,k=0; while(i<=mid&&j<=r){ if(a[i]<a[j]){ temp[k++]=a[i++]; } else{ temp[k++]=a[j++]; sum+=mid-i+1;//求逆序对 } } while(i<=mid) temp[k++]=a[i++]; while(j<=r) temp[k++]=a[j++]; for(ll i=l,k=0;i<=r;k++,i++) a[i]=temp[k]; } void MergeSort(ll a[],ll l,ll r){ ll mid; if(l<r){ mid=(l+r)/2; MergeSort(a,l,mid); MergeSort(a,mid+1,r); Merge(a,l,mid,r); } } int main() { while(~scanf("%lld",&n)) { sum = 0; if(n == 0) break; for(int i = 0; i < n; i++) scanf("%lld",&a[i]); MergeSort(a,0,n-1); printf("%lld\n",sum); } return 0; }