题目描述 Description
涵涵有两盒火柴,每盒装有 n 根火柴,每根火柴都有一个高度。现在将每盒中的火柴各自排成一列,同一列火柴的高度互不相同,两列火柴之间的距离定义为:
,其中 ai表示第一列火柴中第 i 个火柴的高度,bi表示第二列火柴中第 i 个火柴的高度。
每列火柴中相邻两根火柴的位置都可以交换,请你通过交换使得两列火柴之间的距离最小。请问得到这个最小的距离,最少需要交换多少次?如果这个数字太大,请输出这个最小交换次数对 99,999,997 取模的结果。
输入描述 Input Description
共三行,第一行包含一个整数 n,表示每盒中火柴的数目。
第二行有 n 个整数,每两个整数之间用一个空格隔开,表示第一列火柴的高度。
第三行有 n 个整数,每两个整数之间用一个空格隔开,表示第二列火柴的高度。
输出描述 Output Description
输出共一行,包含一个整数,表示最少交换次数对 99,999,997 取模的结果。
样例输入 Sample Input
[Sample 1]
4
2 3 1 4
3 2 1 4
[Sample 2]
4
1 3 4 2
1 7 2 4
样例输出 Sample Output
[Sample 1]
1
[Sample 2]
2
要使两排中对应的火柴差值的平方和最小,那么两排中的第k大值相互对应即可
怎么维护这个关系呢
将两排火柴都进行一遍排序,两排对应的值即是目标状态,如果说目前的火柴所对应的火柴并不是目标状态的火柴,那么就进行交换
暴力维护位置关系显然太慢,这个时候我们就用以当前状态的位置关系为值,进行求逆序对的操作
其中一个数列有几个逆序对,那么就需要多少步完成
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
const int maxn=2333333;
const int mod=99999997;
int xl1[maxn],xl2[maxn];
int lsh1[maxn],lsh2[maxn];
int temp[maxn];
int tong[maxn];
long long ans;
void merge_sort(int l,int r)
{
if(l==r){
return ;
}
int mid=(l+r)/2;
merge_sort(l,mid);
merge_sort(mid+1,r);
int s=l,t=mid+1,p=l;
while(s<=mid&&t<=r){
if(tong[xl1[s]]<tong[xl1[t]]){
temp[p++]=xl1[s];
s++;
}
if(tong[xl1[s]]>tong[xl1[t]]){
temp[p++]=xl1[t];
ans+=(mid-s+1)%mod;
ans%=mod;
t++;
}
}
while(s<=mid){
temp[p++]=xl1[s];
s++;
}
while(t<=r){
temp[p++]=xl1[t];
t++;
}
for(int i=l;i<=r;i++){
xl1[i]=temp[i];
}
}
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++){
scanf("%d",&xl1[i]);
lsh1[i]=xl1[i];
}
for(int i=1;i<=n;i++){
scanf("%d",&xl2[i]);
lsh2[i]=xl2[i];
}
sort(lsh2+1,lsh2+1+n);
sort(lsh1+1,lsh1+1+n);
for(int i=1;i<=n;i++){
int p=lower_bound(lsh1+1,lsh1+1+n,xl1[i])-lsh1;
xl1[i]=p;
}
for(int i=1;i<=n;i++){
int p=lower_bound(lsh2+1,lsh2+1+n,xl2[i])-lsh2;
xl2[i]=p;
}
for(int i=1;i<=n;i++){
tong[xl2[i]]=i;
}
merge_sort(1,n);
/*for(int i=1;i<=n;i++){
cout<<xl1[i]<<" ";
}*/
cout<<ans%mod<<endl;
return 0;
}