天天看點

【Tarjan】UOJ#146 【NOIP2015】資訊傳遞

題面在這裡

Tarjan刷最小環……

示例程式:

#include<cstdio>
#include<algorithm>
using namespace std;
inline char nc(){
    static char buf[],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,,,stdin),p1==p2)?EOF:*p1++;
}
inline int red(){
    int res=,f=;char ch=nc();
    while (ch<'0'||'9'<ch) {if (ch=='-') f=-f;ch=nc();}
    while ('0'<=ch&&ch<='9') res=res*+ch-,ch=nc();
    return res*f;
}

const int maxn=;
int n,ans;
int tot,nxt[maxn],lnk[maxn],son[maxn];
inline void add(int x,int y){
    son[++tot]=y;nxt[tot]=lnk[x];lnk[x]=tot;
}
int dfn[maxn],low[maxn],stk[maxn],times;
bool instk[maxn];
void tarjan(int x){
    dfn[x]=low[x]=++times;
    stk[++stk[]]=x;instk[x]=;
    for (int j=lnk[x];j;j=nxt[j])
     if (!dfn[son[j]]) tarjan(son[j]),low[x]=min(low[x],low[son[j]]);else
     if (instk[son[j]]) low[x]=min(low[x],dfn[son[j]]);
    if (low[x]==dfn[x]){
        int total=;
        while (stk[stk[]+]!=x)
         instk[stk[stk[]--]]=,total++;
        if (total>) ans=min(ans,total);
    }
}
int main(){
    n=red();ans=;
    for (int i=,x;i<=n;i++) x=red(),add(i,x);
    for (int i=;i<=n;i++)
     if (!dfn[i]) tarjan(i);
    printf("%d",ans);
    return ;
}