您的位置:首页 > 其它

noip2014 寻找道路

2016-11-03 18:17 225 查看
const   maxn=10010;
maxm=200010;
var nextt,too:array[0..2*maxm] of longint;
x,y:array[0..maxm] of longint;
head,q,step:array[0..maxn] of longint;
vis:array[0..maxn] of boolean;
n,m,s,t,i,tot:longint;

procedure add(a,b:longint);
begin
inc(tot);
nextt[tot]:=head[a];
too[tot]:=b;
head[a]:=tot;
end;
function f(u:longint):boolean;
var i:longint;
begin
i:=head[u];
while i>0 do begin
if not vis[too[i]] then exit(false);
i:=nextt[i];
end;
exit(true);
end;
function bfs2:boolean;
var l,r,u,i:longint;
begin
q[0]:=s;
step[s]:=0;
l:=0;
r:=1;
while l<r do begin
u:=q[l];
inc(l);
if not f(u) then continue;
i:=head[u];
while i>0 do begin
if step[too[i]]=-1 then begin
step[too[i]]:=step[u]+1;
q[r]:=too[i];
inc(r);
if too[i]=t then begin
writeln(step[too[i]]);
exit(true);
end;
end;
i:=nextt[i];
end;
end;
exit(false);
end;
procedure bfs1;
var l,r,u,i:longint;
begin
q[0]:=t;
vis[t]:=true;
l:=0;
r:=1;
while l<r do begin
u:=q[l];
inc(l);
i:=head[u];
while i>0 do begin
if not vis[too[i]] then begin
vis[too[i]]:=true;
q[r]:=too[i];
inc(r);
end;
i:=nextt[i];
end;
end;
end;
begin
tot:=0;
fillchar(vis,sizeof(vis),false);
fillchar(nextt,sizeof(nextt),0);
fillchar(head,sizeof(head),0);
fillchar(too,sizeof(too),0);
readln(n,m);
for i:=1 to m do begin
readln(x[i],y[i]);
add(y[i],x[i]);
end;
readln(s,t);
bfs1;
fillchar(nextt,sizeof(nextt),0);
fillchar(head,sizeof(head),0);
fillchar(too,sizeof(too),0);
for i:=0 to maxn do step[i]:=-1;
fillchar(q,sizeof(q),0);
tot:=0;
for i:=1 to m do add(x[i],y[i]);
if not vis[s] then writeln(-1)
else if not bfs2 then writeln(-1);

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