noip2014 寻找道路

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.
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值