寻找道路
题目描述
在有向图G 中,每条边的长度均为1 ,现给定起点和终点,请你在图中找一条从起点到终点的路径,该路径满足以下条件:
1 .路径上的所有点的出边所指向的点都直接或间接与终点连通。
2 .在满足条件1 的情况下使路径最短。
注意:图G 中可能存在重边和自环,题目保证终点没有出边。
请你输出符合条件的路径的长度。
输入输出格式
输入格式:
输入文件名为road .in。
第一行有两个用一个空格隔开的整数n 和m ,表示图有n 个点和m 条边。
接下来的m 行每行2 个整数x 、y ,之间用一个空格隔开,表示有一条边从点x 指向点y 。
最后一行有两个用一个空格隔开的整数s 、t ,表示起点为s ,终点为t 。
输出格式:
输出文件名为road .out 。
输出只有一行,包含一个整数,表示满足题目描述的最短路径的长度。如果这样的路径不存在,输出- 1 。
输入输出样例
输入样例#1:
3 2
1 2
2 1
1 3
输出样例#1:
-1
输入样例#2:
6 6
1 2
1 3
2 6
2 5
4 5
3 4
1 5
输出样例#2:
3
说明
解释1:
如上图所示,箭头表示有向道路,圆点表示城市。起点1 与终点3 不连通,所以满足题
目描述的路径不存在,故输出- 1 。
解释2:
如上图所示,满足条件的路径为1 - >3- >4- >5。注意点2 不能在答案路径中,因为点2连了一条边到点6 ,而点6 不与终点5 连通。
对于30%的数据,0
对于60%的数据,0
对于100%的数据,0
有向图的最短路问题,第一次bfs判连通。
我并不会对第二次搜索起名,就是基于第一次bfs的一个最短路吧。
1 #include
2 #include
3 #include
4 #include
5 #include
6 using namespace std;
7 int n,m,s,e,cnt;
8 int a[200010],b[200010],head[10010],w[10010];
9 bool check[10010];
10 struct data{
11 int nex,to;
12 }edge[200010];
13 void add(int start,int end){
14 edge[++cnt].nex=head[start];
15 edge[cnt].to=end;
16 head[start]=cnt;
17 }
18 void bfs(){
19 queue<int>q;
20 q.push(e);
21 check[e]=1;
22 while(!q.empty()){
23 int p=q.front();
24 q.pop();
25 for(int i=head[p];i;i=edge[i].nex)
26 if(!check[edge[i].to]){
27 q.push(edge[i].to);
28 check[edge[i].to]=1;
29 }
30 }
31 }
32 bool judge(int x){
33 for(int i=head[x];i;i=edge[i].nex)
34 if(!check[edge[i].to]) return 0;
35 return 1;
36 }
37 void bfsbfs(){
38 queue<int>q;
39 memset(w,0x3f3f3f3f,sizeof(w));
40 w[s]=0;
41 q.push(s);
42 while(!q.empty()){
43 int p=q.front();
44 q.pop();
45 if(!judge(p)) continue;
46 for(int i=head[p];i;i=edge[i].nex)
47 if(w[edge[i].to]==0x3f3f3f3f){
48 w[edge[i].to]=w[p]+1;
49 q.push(edge[i].to);
50 }
51 }
52 }
53 int main(){
54 scanf("%d%d",&n,&m);
55 for(int i=1;i<=m;i++){
56 scanf("%d%d",&a[i],&b[i]);
57 add(b[i],a[i]);
58 }
59 scanf("%d%d",&s,&e);
60 bfs();
61 if(!check[s]){
62 printf("-1\n");
63 return 0;
64 }
65 cnt=0;
66 memset(edge,0,sizeof(edge));
67 memset(head,0,sizeof(head));
68 for(int i=1;i<=m;i++) add(a[i],b[i]);
69 bfsbfs();
70 if(w[e]!=0x3f3f3f3f) printf("%d\n",w[e]);
71 else printf("-1\n");
72 return 0;
73 }