求助0分
查看原帖
求助0分
474235
LeTu_Jun楼主2021/11/10 12:10
#include<bits/stdc++.h>
using namespace std;
const int N=200005;
int f[N],l[N];
int n,ans;
int find (int x)
{
	if(f[x]!=x)
	{
		int lst=f[x];
		f[x]=find(f[x]);
		l[x]+=l[lst];
	}
	return f[x];
}
void check (int x,int y)
{
	x=find(x);
	y=find(y);
	if(x!=y)
	{
		f[x]=y;
		l[x]=l[y]+1;
	}
	else 
	{
		ans=min(ans,l[x]+l[y]+1);
	}
	return ;
}
void Initialization ()
{
	for(int i=1;i<=n;i++){
		f[i]=i;
	}
	ans=1e10+5;
	return ;
}
int main ()
{
	scanf("%d",&n);
	Initialization();
	for(int i=1,j;i<=n;i++){
        scanf("%d",&j);
        check(i,j);                     
    }
    printf("%d",ans);
    return 0;
}

感谢

本人可能一段时间后再回来,如若没有回复请勿喷

2021/11/10 12:10
加载中...