算法要素:并查集的奇妙应用
思路:
并查集求有向图最小环
tips:这道题完全可以拓展成带边权的有向图最小环,原题相当于边权为1.
Code
#include<bits/stdc++.h>
using namespace std;
const int maxn=2e5+50;
int fa[maxn],dis[maxn];
int n,t[maxn];
int minn=1e9+7;
int Find(int x)
{
if(fa[x]!=x)
{
int last=fa[x];
fa[x]=Find(fa[x]);
dis[x]+=dis[last];
}
return fa[x];
}
void check(int x,int y)
{
int xx=Find(x),yy=Find(y);
if(xx!=yy)
{
dis[x]=dis[y]+1;
fa[xx]=yy;
}
else minn=min(minn,dis[y]+dis[x]+1);
return;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;++i) scanf("%d",&t[i]);
for(int i=1;i<=n;++i) fa[i]=i;
for(int i=1;i<=n;++i)
{
check(i,t[i]);
}
printf("%d",minn);
return 0;
}