两列排序后将编号一一对应
归并排序求逆序对
(每一次交换就去掉一个逆序对)
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #define ll long long 5 using namespace std; 6 const int N=100100; 7 const ll P=99999997; 8 ll tmp[N],ss[N],ans,n; 9 struct fx{ 10 ll w; 11 int id; 12 }a[N],b[N]; 13 bool cmp(fx p,fx q){ 14 return p.w<q.w; 15 } 16 ll read(){ 17 ll sum=0; 18 char ch=getchar(); 19 while (ch<'0'||ch>'9') 20 ch=getchar(); 21 while (ch>='0'&&ch<='9'){ 22 sum=sum*10+ch-'0'; 23 ch=getchar(); 24 } 25 return sum; 26 } 27 void mergesort(int l,int r){ 28 if(l==r) 29 return; 30 int m=(l+r)>>1; 31 mergesort(l,m); 32 mergesort(m+1,r); 33 int i=l; 34 int j=m+1; 35 int k=l; 36 while (i<=m&&j<=r){ 37 if (ss[i]<ss[j]){ 38 tmp[k]=ss[i]; 39 i++; 40 k++; 41 } 42 else{ 43 ans=(ans+m-i+1)%P;//区间内逆序对个数 44 tmp[k]=ss[j]; 45 j++; 46 k++; 47 } 48 } 49 while (i<=m){ 50 tmp[k]=ss[i]; 51 k++; 52 i++; 53 } 54 while (j<=r){ 55 tmp[k]=ss[j]; 56 k++; 57 j++; 58 } 59 for (int i=l;i<=r;i++){ 60 ss[i]=tmp[i]; 61 } 62 } 63 int main(){ 64 ans=0; 65 n=read(); 66 for (int i=1;i<=n;i++){ 67 a[i].w=read(); 68 a[i].id=i; 69 } 70 for (int i=1;i<=n;i++){ 71 b[i].w=read(); 72 b[i].id=i; 73 } 74 sort(a+1,a+n+1,cmp); 75 sort(b+1,b+n+1,cmp); 76 for (int i=1;i<=n;i++) 77 ss[a[i].id]=b[i].id; 78 mergesort(1,n); 79 printf("%lld",ans%P); 80 return 0; 81 }