归并排序与逆序对
作者:互联网
归并
逆序对
#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; }View Code
标签:归并,排序,int,mid,long,msort,while,include,逆序 来源: https://www.cnblogs.com/Frost-Delay/p/11509055.html