并查集裸题,记录每个点的胜读,取个min就好了
#include#include #include using namespace std;int fa[200007],dep[200007],n,x,a,mn=1e9+7;template void read(T &x){ int f=0;x=0;char ch=getchar(); while(ch<'0'||ch>'9') {f|=(ch=='-');ch=getchar();} while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();} x=f?-x:x;}int find(int x){ if(fa[x]!=x) {int t=fa[x];fa[x]=find(fa[x]);dep[x]+=dep[t];} return fa[x];}void yhh(int a,int b){ int x=find(a),y=find(b); if(x!=y) fa[x]=y,dep[a]=dep[b]+1; else mn=min(mn,dep[a]+dep[b]+1);}int main(){ read(n); for(int i=1;i<=n;++i) fa[i]=i; for(int i=1;i<=n;++i) read(x),yhh(i,x); printf("%d",mn); return 0;}