https://www.luogu.org/problemnew/show/P1908
递归与分治
其实只需要在归并排序的时候加上一个计数的语句就好啦
#include<bits/stdc++.h> using namespace std; long long int n,a[500005],c[500005],sums; //题目数据有点大 需要long long void guibing(int s,int e) { if(s==e) return; int mid=(s+e)/2,i=s,j=mid+1,k=s; guibing(i,mid),guibing(j,e); while(i<=mid&&j<=e) { if(a[i]<=a[j]) c[k++]=a[i++]; else { c[k++]=a[j++]; sums+=mid-i+1; //计数 } } while(i<=mid) c[k++]=a[i++]; while(j<=e) c[k++]=a[j++]; for(i=s;i<=e;i++) a[i]=c[i]; //将排好序的复制回去 return; } int main() { int i; cin>>n; for(i=1;i<=n;i++) cin>>a[i]; guibing(1,n); cout<<sums; }