解题思路
好了回归题目,既然要求找到
m
i
n
(
Σ
[
(
a
i
−
b
i
)
2
]
)
min(Σ[(ai-bi)^2])
min(Σ[(ai−bi)2]),那么我们不妨变形一下:
Σ
[
(
a
i
−
b
i
)
2
]
=
Σ
(
a
i
2
−
2
∗
a
i
∗
b
i
+
b
i
2
)
Σ[(ai-bi)^2]=Σ(ai^2-2*ai*bi+bi^2)
Σ[(ai−bi)2]=Σ(ai2−2∗ai∗bi+bi2)
由此可见,若想使
m
i
n
(
Σ
[
(
a
i
−
b
i
)
2
]
)
min(Σ[(ai-bi)^2])
min(Σ[(ai−bi)2])最小,而和式中
a
i
2
+
b
i
2
ai^2+bi^2
ai2+bi2是个定值,那么,就只能想办法让
Σ
2
∗
a
i
b
i
Σ2*aibi
Σ2∗aibi 这一项最大
经过排序+离散化之后,假设得到了这样两个序列:
A
:
(
1
,
3
,
4
,
2
)
和
B
:
(
1
,
4
,
2
,
3
)
A:(1,3,4,2)和B:(1,4,2,3)
A:(1,3,4,2)和B:(1,4,2,3)。
我们要让A的第1大对应B的第1大,A的第2大对应B的第2大,A的第n大对应B的第n大.
我们以 a [ i ] a[i] a[i]为关键字对 b [ i ] b[i] b[i]排序,令 x [ a [ i ] ] = b [ i ] x[a[i]]=b[i] x[a[i]]=b[i],在a和b中构造一种映射关系。
若序列a与序列b相等,那么此时 x [ a [ i ] ] x[a[i]] x[a[i]]应该等于a[i]的,也就是 x [ i ] = i x[i]=i x[i]=i。那么也就是说如果我们想让序列a与序列b相等,那么我们需要让 x x x升序排列。
问题就变为:将原本乱的X序列升序排列的最少交换次数=求X序列的逆序对个数。
代码
#include<cstdio>
#include<iostream>
#include<queue>
#include<algorithm>
#include<cstring>
#include<cmath>
#define ll long long
using namespace std;
const int mod=1e8-3;
int n,ans,w[1000010],s[1000010];
struct c{
int x,id;
}a[100010],b[100010];
bool cmp(c l,c r)
{
return l.x<r.x;
}
void work(int l,int r)
{
int mid=(l+r)/2;
int i=l,j=mid+1,tot=l;
while(i<=mid&&j<=r)
{
if(w[i]<=w[j])
s[tot++]=w[i++];
else
{
s[tot++]=w[j++];
ans=(ans+mid-i+1)%mod;
}
}
while(i<=mid)
s[tot++]=w[i++];
while(j<=r)
s[tot++]=w[j++];
for(int i=l;i<=r;i++)
w[i]=s[i];
}
void px(int l,int r)
{
if(l==r)return;
int mid=(l+r)/2;
px(l,mid);
px(mid+1,r);
work(l,r);
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i].x);
a[i].id=i;
}
for(int i=1;i<=n;i++)
{
scanf("%d",&b[i].x);
b[i].id=i;
}
sort(a+1,a+n+1,cmp);
sort(b+1,b+n+1,cmp);
for(int i=1;i<=n;i++)
w[b[i].id]=a[i].id;
px(1,n);
printf("%d",ans);
}