HDU ACM 1269 迷宫城堡 (Tarjan,DFS)

http://acm.hdu.edu.cn/showproblem.php?pid=1269

思路:Tarjan算法,模版题

 

 1 #include <iostream>
 2 #include <vector>
 3 #include <stack>
 4 using namespace std;
 5 const int MAX = 10000 + 10;
 6 int n;
 7 vector <int> v[MAX];
 8 stack <int> s;
 9 int mark_stack[MAX];
10 int dfn[MAX];
11 int low[MAX];
12 int time;
13 int sum;
14 void Tarjan(int rank){
15     dfn[rank] = low[rank] = ++time;
16     s.push(rank);
17     mark_stack[rank] = 1;
18     int i;
19     for(i=0;i<v[rank].size();i++){
20         if(!dfn[v[rank][i]]){
21             Tarjan(v[rank][i]);
22             low[rank] = min(low[rank],low[v[rank][i]]);
23         }
24         else{
25             if(mark_stack[v[rank][i]]){
26                 low[rank] = min(low[rank],dfn[v[rank][i]]);
27             }
28         }
29     }
30     if(low[rank] == dfn[rank]){
31         sum++;
32         int x = s.top();
33         mark_stack[x] = 0;
34         s.pop();
35         while(x != rank){
36             x = s.top();
37             mark_stack[x] = 0;            
38             s.pop();
39         }
40     }
41     
42 }
43 int main(){
44     int m;
45     while(cin>>n>>m,n+m){
46         while(!s.empty()){
47             s.pop();
48         }
49         int i;
50         for(i=0;i<MAX;i++){
51             v[i].clear();
52         }
53         memset(dfn,0,sizeof(dfn));
54         memset(low,0,sizeof(low));
55         memset(mark_stack,0,sizeof(mark_stack));
56         while(m--){
57             int x,y;
58             cin>>x>>y;
59             v[x].push_back(y);
60         }
61         sum = 0;
62         time = 0;
63         for(i=1;i<=n;i++){
64             if(!dfn[i]){
65                 if(sum){
66                     sum++;
67                     break;
68                 }
69                 else{
70                     Tarjan(1);
71                 }
72             }
73 
74         }
75         if(sum == 1){
76             cout<<"Yes"<<endl;
77         }
78         else{
79             cout<<"No"<<endl;
80         }
81     }
82     return 0;
83 }

 

posted @ 2013-03-16 11:36  zx雄  阅读(594)  评论(0编辑  收藏  举报