CF1677C题解
题目传送门:CF1677C
题意简述:
给予两个
做法详解
由于答案跟编号的顺序无关,我们不妨把每个数字重新编号。即:将
那么我们此时考虑一个环内的情况。若当前的数为
由此,不难发现,对于一个大小为
那么对于奇环呢?其实也是一样有
结果是明了的,我们只需要找出每一个环,计算出它的大小
具体实现上,图上有且仅有环,记录一个
代码
#include<bits/stdc++.h>
#define ll long long
const int N=2e5+7;
using namespace std;
int n,a[N],b[N],cir[N],tot,pos[N];
ll ans;
bool vis[N];
void solve()
{
ans=tot=0;
cin>>n;
memset(vis,0,sizeof(int)*(n+3));
for(int i = 1;i<= n;i++) cin>>b[i],pos[b[i]]=i;
for(int i = 1;i<= n;i++) cin>>a[i],a[i]=pos[a[i]];
for(int i = 1;i<= n;i++)
{
int cnt=0,x=i;
while(!vis[x]) cnt++,vis[x]=1,x=a[x];
cir[++tot]=cnt;
}
int x=n,y=1;
for(int i = 1;i<= n;i++)
{
int k=cir[i]/2,t=k;
while(t--) ans+=2*x,x--;
t=k;
while(t--) ans-=2*y,y++;
}
cout<<ans<<'\n';
}
int main()
{
ios::sync_with_stdio(0),cin.tie(0);
int t;cin>>t;
while(t--) solve();
}