HDU1269 (tarjan)

View Code
 1 #include<stdio.h>
 2 #include<stack>
 3 #include<string.h>
 4 #include<stdlib.h>
 5 #include<algorithm>
 6 using namespace std;
 7 const int maxn = 10005;
 8 const int maxm = 100005;
 9 struct node{
10     int u,next;
11 }edge[ maxm ];
12 int head[ maxn ],cnt;
13 int vis[ maxn ],dfn[ maxn ],low[ maxn ],cnt2,id;
14 int n,m;
15 
16 void init(){
17     cnt=0;
18     id=0;
19     cnt2=0;
20     memset( head,-1,sizeof( head ));
21     memset( vis,0,sizeof( vis ));
22     memset( dfn,-1,sizeof( dfn ));
23     memset( low,0,sizeof( low ));
24 }
25 void addedge( int a,int b ){
26     edge[ cnt ].u=b;
27     edge[ cnt ].next=head[ a ];
28     head[ a ]=cnt++;
29 }
30 stack<int>s;
31 
32 void tarjan( int now ){
33     dfn[ now ]=low[ now ]=id++;
34     vis[ now ]=1;
35     s.push( now );
36     for( int i=head[ now ];i!=-1;i=edge[ i ].next ){
37         int next=edge[ i ].u;
38         if( dfn[ next ]==-1 ){
39             tarjan( next );
40             low[ now ]=min( low[ now ],low[ next ] );
41         }
42         else if( vis[ next ]==1 ){
43             low[ now ]=min( low[ now ],dfn[ next ] );
44         }
45     }
46     if( dfn[ now ]==low[ now ] ){
47         cnt2++;
48         while( 1 ){
49             int tmp=s.top();
50             s.pop();
51             vis[ tmp ]=0;
52             if( tmp==now ) break;
53         }
54     }
55 }
56 
57 int main(){
58     while( scanf("%d%d",&n,&m)==2 &&(n+m) ){
59         init();
60         int a,b;
61         while( m-- ){
62             scanf("%d%d",&a,&b);
63             addedge( a,b );
64         }
65         for( int i=1;i<=n;i++ )
66             if( dfn[ i ]==-1 )
67                 tarjan( i );
68         if( cnt2==1 ) printf("Yes\n");
69         else printf("No\n");
70     }
71     return 0;
72 }
keep moving...
原文地址:https://www.cnblogs.com/xxx0624/p/2890513.html