Luo Gu P2661 messaging - disjoint-set

To single-handedly link https://www.luogu.com.cn/problem/P2661 

This question is disjoint-set ring for the Minimum

TIPS: compression path when d [x] = d [fa [x]] + d [x], rather than the d [x] = d [fa [x]] + 1 because the path is compressed

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<cmath>
using namespace std;
const int M=1e6+7;
int read(){
    int ans=0,f=1,c=getchar();
    while(c<'0'||c>'9'){if(c=='-') f=-1; c=getchar();}
    while(c>='0'&&c<='9'){ans=ans*10+(c-'0'); c=getchar();}
    return ans*f;
}
int n,T,f[M],d[M];
int find(int x){
    int F=f[x];
    if(F==x) return F;
    f[x]=find(F);
    d[x]=d[F]+d[x];
    return f[x];
}
int ans=M;
int main(){
    n=read();
    for(int i=1;i<=n;i++) f[i]=i,d[i]=0;
    for(int i=1;i<=n;i++){
        T=read();
        int q=find(T);
        if(i==q) ans=min(ans,d[i]+d[T]+1);
        else f[i]=q,d[i]=d[T]+1;
    }
    printf("%d\n",ans);
    return 0;
}
View Code

 

Guess you like

Origin www.cnblogs.com/yourinA/p/12000335.html