【洛谷P2296】寻找道路

反正图两边bfs

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<queue>
 4 
 5 using namespace std;
 6 
 7 inline int readint(){
 8     int x=0,f=1;
 9     char ch=getchar();
10     while (ch<'0'||ch>'9'){
11         if (ch=='-') f=-1;
12         ch=getchar();
13     }
14     while (ch>='0'&&ch<='9'){
15         x=(x<<1)+(x<<3)+ch-'0';
16         ch=getchar();
17     }
18     return x*f;
19 }
20 struct edge{
21     int x,nxt;
22 }e1[410001],e2[410001];
23 
24 int n,m,s,t,t1,t2,kk,inq[50001],v[50001],tmp,sg=0,v2[50001],v1[50001],cnt,head1[50001],head2[50001];
25 struct node{
26     int x,p;
27 }now;
28 inline void adde1(int a,int b){
29     ++cnt;
30     e1[cnt].x=b;
31     e1[cnt].nxt=head1[a];
32     head1[a]=cnt;
33 }inline void adde2(int a,int b){
34     ++cnt;
35     e2[cnt].x=b;
36     e2[cnt].nxt=head2[a];
37     head2[a]=cnt;
38 }
39 queue <node> q;
40 queue <int> qq;
41 int main(){
42     n=readint();
43     m=readint();
44     for (int i=1;i<=m;++i){
45         t1=readint();
46         t2=readint();
47         adde1(t1,t2);
48         adde2(t2,t1);
49     }
50     s=readint();
51     t=readint();
52     kk=t;
53     inq[kk]=1;
54     qq.push(kk);
55     while (!qq.empty()){
56         kk=qq.front();
57         qq.pop();
58         inq[kk]=0;
59         v1[kk]=1;
60         for (int i=head2[kk];i;i=e2[i].nxt){
61             tmp=e2[i].x;
62             if ((!inq[tmp])&&(!v1[tmp])) qq.push(tmp);
63         }
64     }
65     for (int i=1;i<=n;++i) v[i]=v1[i];
66     for (int i=1;i<=n;++i) {
67         if (v1[i]==0) {
68             v[i]=0;
69             for (int j=head2[i];j;j=e2[j].nxt){
70                 v[e2[j].x]=0;
71             }
72         }
73             
74     }
75     q.push((node){s,0});
76     while (!q.empty()){
77         now=q.front();
78         q.pop();
79         v2[now.x]=1;
80         if (now.x==t) printf("%d",now.p),sg=1;
81         if (sg==1) break;
82         for (int i=head1[now.x];i;i=e1[i].nxt){
83             tmp=e1[i].x;
84             if (v[tmp]==1&&v2[tmp]==0) {
85                 q.push((node){tmp,now.p+1});
86             }
87         }
88     }
89     if (sg==0) printf("-1\n");
90 }
STD

 

转载于:https://www.cnblogs.com/Absolute-Zero/p/6016941.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值