归并排序+逆序数(模板)
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int MAXN=1e5+10; 4 int a[MAXN]; 5 int temp[MAXN]; 6 long long ans; 7 void merge(int l,int mid,int r) 8 { 9 int i=l; 10 int j=mid+1; 11 int k=l; 12 while(i<=mid&&j<=r) 13 { 14 if(a[i]<=a[j]) 15 { 16 temp[k++]=a[i++]; 17 } 18 else 19 { 20 ans+=j-k;//记录数量; 21 temp[k++]=a[j++]; 22 } 23 } 24 while(i<=mid) 25 temp[k++]=a[i++]; 26 while(j<=r) 27 temp[k++]=a[j++]; 28 for (int s = l; s <=r; ++s) { 29 a[s]=temp[s]; 30 } 31 32 } 33 34 void mergesort(int l,int r) 35 { 36 if(l<r) 37 { 38 int mid=(l+r)/2; 39 mergesort(l,mid); 40 mergesort(mid+1,r); 41 merge(l,mid,r); 42 } 43 } 44 int main() 45 { 46 int n,x,y; 47 while(scanf("%d%d%d",&n,&x,&y)!=EOF) { 48 ans=0; 49 memset(temp,0,sizeof(temp)); 50 for (int i = 0; i <n ; ++i) { 51 scanf("%d",&a[i]); 52 } 53 mergesort(0,n-1); 54 printf("%lld\n",ans); 55 } 56 return 0; 57 }