PTA Sort with Swap(0, i)

链接

https://pintia.cn/problem-sets/994805342720868352/problems/994805402305150976

题解

众所周知,一个置换对应的图一定是若干个基本环
对于一个包含 0 0 0的环,假设大小为 k ( k > 1 ) k(k>1) k(k>1),那么我需要花 k − 1 k-1 k1次交换才能使之变成目标状态
对于一个不包含 0 0 0的环,假设其大小为 k ( k > 1 ) k(k>1) k(k>1),我需要先花费 1 1 1次交换把 0 0 0添加到这个环中,然后再花 k + 1 − 1 = k k+1-1=k k+11=k次交换使之变成目标状态

代码

#include <bits/stdc++.h>
#define maxn 100010
#define iinf 0x3f3f3f3f
#define linf 0x3f3f3f3f3f3f3f3fll
#define ll long long
using namespace std;
ll f[maxn], g[maxn], N, cnt, ans, vis[maxn], d;
ll read(ll x=0)
{
	ll c, f=1;
	for(c=getchar();!isdigit(c);c=getchar())if(c=='-')f=-f;
	for(;isdigit(c);c=getchar())x=x*10+c-48;
	return f*x;
}
void init()
{
	ll i;
	N = read();
	for(i=0;i<N;i++)
	{
		f[i] = read();
		g[f[i]]=i;
	}
}
void dfs(ll pos)
{
	cnt++;
	if(pos==0)d=-1;
	vis[pos]=true;
	if(!vis[g[pos]])dfs(g[pos]);
}
int main()
{
	ll i;
	init();
	for(i=0;i<N;i++)
		if(!vis[i])
		{
			cnt=0;
			d=1;
			dfs(i);
			if(cnt>1)ans+=cnt+d;
		}
	printf("%lld",ans);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值