首页 > 其他 > 详细

sicily 1155 Can I Post the letter

时间:2014-01-14 19:46:23      阅读:618      评论:0      收藏:0      [点我收藏+]

题意:判断有向图两点之间是否可通达!

解法:深搜或广搜(注意避免旧路重行)

  

   DFS:

bubuko.com,布布扣
 1 #include<iostream>
 2 #include<vector>
 3 #include<string.h>
 4 using namespace std;
 5 
 6 struct Road{
 7     int From;
 8     int Dest;
 9     bool Vist;
10     Road(int f,int d,bool v){
11         From = f;
12         Dest = d;
13         Vist = v;
14     }
15 };
16 vector<Road> roads[20001];
17 bool reach=false;
18 int N,M;
19 
20 void dfs(int n){
21     if(n == N-1){
22         reach = true;
23         return;
24     }
25     for(int i=0;i<roads[n].size();i++){
26         if(roads[n][i].Vist && roads[n][i].Dest !=0){
27             int gonext =roads[n][i].Dest;
28             //use to avoid repeat search
29             roads[n][i].Vist = false;    
30             dfs(gonext);
31         }
32     }
33 }
34 int main(){
35     while(cin>>N && N>0){
36         cin>>M;
37         reach = false;
38         memset(roads,0,sizeof(roads));
39         int from,dest;
40         bool exist = true;
41         for(int i=0;i<M;i++){
42             cin >> from>>dest;
43             Road r = Road(from,dest,exist);
44             roads[from].push_back(r);
45         }
46         //deep search
47         dfs(0);
48         if(reach){
49             cout<<"I can post the letter"<<endl;
50         }
51         else{
52             cout<<"I can‘t post the letter"<<endl;
53         }
54     }
55     return 0;
56 }
bubuko.com,布布扣

       BFS:

bubuko.com,布布扣
 1 #include<iostream>
 2 #include<string.h>
 3 #include<queue>
 4 using namespace std;
 5 
 6 int N,M;
 7 int roads[201][201];
 8 bool visited[200001];
 9 
10 int main(){
11     while(cin>>N && N>0){
12         cin>>M;
13         memset(roads,0,sizeof(roads));
14         memset(visited,false,sizeof(visited));
15         int from=0,dest=0;
16         for(int i=0;i<M;i++){
17             cin >> from>>dest;
18             roads[from][dest] = 1;
19         }
20         //breadth-first search
21         queue<int> que;
22         que.push(0);
23         int i;
24         while(!que.empty() && visited[N-1] !=true){
25             i = que.front();
26             for(int j=0;j<N;j++){
27                 if(roads[i][j] == 1 && visited[j] == false)
28                 {
29                     visited[j] = true;
30                     que.push(j);
31                 }
32             }
33             que.pop();
34         }
35         if(visited[N-1] == true){
36             cout<<"I can post the letter"<<endl;
37         }
38         else{
39             cout<<"I can‘t post the letter"<<endl;
40         }
41     }
42     return 0;
43 }
bubuko.com,布布扣

sicily 1155 Can I Post the letter

原文:http://www.cnblogs.com/renaissance/p/3512831.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!