noip2015 信息传递

const maxn=200000;
var fa,son,q:array[0..maxn] of longint;
    vis:array[0..maxn] of boolean;
    l,r,i,n,x,ans:longint;
function min(a,b:longint):longint;
begin
    if athen exit(a) else exit(b);
end;
procedure dfs(n,k,st:longint);
begin
    if (n=k) and (st>1) then begin ans:=min(ans,st-1); exit; end; 
    vis[n]:=false;
    dfs(fa[n],k,st+1);
end;
begin
    fillchar(vis,sizeof(vis),true);
    fillchar(son,sizeof(son),0);
    readln(n);
    for i:=1 to n do begin
        read(fa[i]);
        inc(son[fa[i]]);
    end;
    l:=1;r:=1;
    for i:=1 to n do if son[i]=0 then begin
        q[r]:=i;
        inc(r);
    end;
    while l<=r do begin
        x:=q[l];
        vis[x]:=false;
        dec(son[fa[x]]);
        if son[fa[x]]=0 then begin q[r]:=fa[x]; inc(r); end;
        inc(l);
    end;
    ans:=maxlongint;
    for i:=1 to n do if vis[i] then dfs(i,i,1);
    writeln(ans);
end.

你可能感兴趣的:(历年noip)