归并排序与逆序对
归并
逆序对
#include<iostream> #include<cstdio> #include<cctype> using namespace std; inline long long read() { long long x=0,f=1;char c=getchar(); while(!isdigit(c)){if(c=='-')f=-1;c=getchar();} while(isdigit(c)){x=(x<<3)+(x<<1)+(c^48);c=getchar();} return x*f; } long long a[500001],r[500001],n,ans; inline void msort(int i,int j) { if(i==j)return; int mid=i+j>>1; msort(i,mid); msort(mid+1,j); int x=i,y=mid+1; for(int k=i;k<=j;k++) if((y>j)||(x<=mid&&a[x]<=a[y]))r[k]=a[x++]; else r[k]=a[y++],ans+=mid-x+1; for(int p=i;p<=j;p++)a[p]=r[p]; return; } int main() { n=read(); for(int i=1;i<=n;i++) a[i]=read(); msort(1,n); printf("%lld\n",ans); return 0; }