涵涵有两盒火柴,每盒装有 \(n\) 根火柴,每根火柴都有一个高度。 现在将每盒中的火柴各自排成一列, 同一列火柴的高度互不相同, 两列火柴之间的距离定义为:\(\sum (a_i-b_i)^2\)
其中 \(a_{i}\)? 表示第一列火柴中第 \(i\)个火柴的高度,\(b_i\) 表示第二列火柴中第 \(i\) 个火柴的高度。
每列火柴中相邻两根火柴的位置都可以交换,请你通过交换使得两列火柴之间的距离最小。请问得到这个最小的距离,最少需要交换多少次?如果这个数字太大,请输出这个最小交换次数对 \(10^8-3\) 取模的结果。
共三行,第一行包含一个整数 \(n\),表示每盒中火柴的数目。
第二行有 \(n\) 个整数,每两个整数之间用一个空格隔开,表示第一列火柴的高度。
第三行有 \(n\) 个整数,每两个整数之间用一个空格隔开,表示第二列火柴的高度。
一个整数,表示最少交换次数对 \(10^8-3\) 取模的结果。
4
2 3 1 4
3 2 1 4
1
4
1 3 4 2
1 7 2 4
2
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define N 500010
using namespace std;
inline int read(){
int x = 0,f = 1;
char ch = getchar();
while(ch>‘9‘||ch<‘0‘){if(ch==‘-‘)f=-1;ch=getchar();}
while(ch>=‘0‘&&ch<=‘9‘){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
return x*f;
}
const int mod = 99999997;
int n,c[N],ans,tree[N];
struct node{
int num,id;
}a[N],b[N];
bool cmp(node a,node b){
return a.num < b.num;
}
int lowbit(int x){
return x & (-x);
}
void update(int x,int val){
while(x <= n){
tree[x] += val;
x += lowbit(x);
}
}
int getsum(int x){
int res = 0;
while(x > 0){
res += tree[x];
x -= lowbit(x);
}
return res;
}
int main(){
n = read();
for(int i = 1;i <= n;i++){
a[i].num = read();
a[i].id = i;
}
for(int i = 1;i <= n;i++){
b[i].num = read();
b[i].id = i;
}
sort(a+1,a+1+n,cmp);
sort(b+1,b+1+n,cmp);
for(int i = 1;i <= n;i++){
c[a[i].id] = b[i].id;
}
for(int i = 1;i <= n;i++){ //树状数组求逆序对
update(c[i],1);
ans = (ans+i-getsum(c[i]))%mod;
}
printf("%d\n",ans);
return 0;
}
原文:https://www.cnblogs.com/hhhhalo/p/13390689.html