归并排序之逆序对
推荐大佬博客:https://www.cnblogs.com/adelalove/p/8484644.html
本人水平有限,题解不到为处,请多多谅解
本蒟蒻谢谢大家观看
题目:NOIP2013火柴排队
code:
#include<bits/stdc++.h> #pragma GCC optimize(3) #define mod 99999997 using namespace std; int n,c[100005],d[100005],ans; inline int read(){ int x=0,f=1;char ch=getchar(); while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();} while(isdigit(ch)){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();} return x*f; } struct node { int n,id; }a[100005],b[100005]; void msort(int l,int r) { if(l>=r) return; int m=(l+r)/2; msort(l,m); msort(m+1,r); int i=l,j=m+1,k=l; while(i<=m && j<=r) { if(c[i]>c[j]) { d[k++]=c[j++]; ans+=m-i+1;//求逆序对 ans%=mod;//题目要求 } else { d[k++]=c[i++]; } } while(i<=m) d[k++]=c[i++]; while(j<=r) d[k++]=c[j++]; for(i=l;i<=r;i++) { c[i]=d[i]; //cout<<"c[i]= "<<c[i]<<endl; } } bool mcmp(node x,node y) { return x.n<y.n; } int main(){ n=read(); int i; for(i=1;i<=n;i++) { a[i].n=read(); a[i].id=i; } for(i=1;i<=n;i++) { b[i].n=read(); b[i].id=i; //cout<<"b[i].id 22 == "<<b[i].id<<endl; } sort(a+1,a+n+1,mcmp); sort(b+1,b+n+1,mcmp); for(i=1;i<=n;i++) { // cout<<"b[i].id= "<<b[i].id<<endl; c[a[i].id]=b[i].id; //cout<<"a[i].id= "<<a[i].id<<endl; //cout<<"c[a[i].id]= "<<c[a[i].id]<<endl;//<<" b[i].id= "<<b[i].id<<endl; } msort(1,n); //for(int i=1;i<=n;i++) //cout<<"c[i]= "<<c[i]<<endl; printf("%d\n",ans); return 0; }