首页 > 代码库 > 【洛谷P2296】寻找道路
【洛谷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 }
【洛谷P2296】寻找道路
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。