您的位置:首页 > 其它

NOIP2015信息传递

2016-11-08 07:05 288 查看
Tarjan求最小生成环(注意要形成一个环而不是一个点,即size>1),这真的很模板...

var
n,x,l,time,top,t,minn:longint;
i :longint;
dfn,low,z,size :array[0..200010] of longint;
last,pre,other :array[0..200010] of longint;
vis :array[0..200010] of boolean;
function min(a,b:longint):longint;
begin
if a<b then exit(a) else exit(b);
end;

procedure connect(x,y:longint);
begin
inc(l);
pre[l]:=last[x];
last[x]:=l;
other[l]:=y;
end;

procedure dfs(x:longint);
var
p,q,cur:longint;
begin
inc(time);
low[x]:=time;
dfn[x]:=time;
vis[x]:=true;
inc(top);
z[top]:=x;
//
q:=last[x];
while (q<>0) do
begin
p:=other[q];
if (dfn[p]=0) then
begin
dfs(p);
low[x]:=min(low[x],low[p]);
end else
if vis[p] then low[x]:=min(low[x],dfn[p]);
q:=pre[q];
end;
//
if (dfn[x]=low[x]) then
begin
cur:=-1;inc(t);
while (cur<>x) do
begin
cur:=z[top];
dec(top);
vis[cur]:=false;
inc(size[t]);
end;
end;
end;

begin
read(n);
for i:=1 to n do
begin
read(x);
connect(i,x);
end;
//
for i:=1 to n do if (dfn[i]=0) then dfs(i);
minn:=maxlongint;
for i:=1 to t do
if (size[i]<minn) and (size[i]>1) then minn:=size[i];
writeln(minn);
end.

——by Eirlys
转载请注明出处=w=

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息