hdu 1269 tarjan求强连通分量

tarjan求强连通分量的裸题复习,直接上代码:

 1 #include <stack>

 2 #include <cstdio>

 3 #include <cstring>

 4 using namespace std;

 5 

 6 const int N = 10001;

 7 const int M = 100000;

 8 int dfn[N], low[N], head[N];

 9 bool inStack[N];

10 int n, m, e, cnt, dfs_clock;

11 stack<int> s;

12 

13 struct Edge 

14 {

15     int v, next;

16 } edge[M];

17 

18 void init()

19 {

20     e = cnt = dfs_clock = 0;

21     memset( head, -1, sizeof(head) );

22     memset( dfn, 0, sizeof(dfn) );

23     memset( inStack, 0, sizeof(inStack) );

24 }

25 

26 void addEdge( int u, int v )

27 {

28     edge[e].v = v;

29     edge[e].next = head[u];

30     head[u] = e++;

31 }

32 

33 void dfs( int u )

34 {

35     dfn[u] = low[u] = ++dfs_clock;

36     inStack[u] = true;

37     s.push(u);

38     for ( int i = head[u]; i != -1; i = edge[i].next )

39     {

40         int v = edge[i].v;

41         if ( dfn[v] == 0 )

42         {

43             dfs(v);

44             if ( low[v] < low[u] )

45             {

46                 low[u] = low[v];

47             }

48         }

49         else if ( inStack[v] )

50         {

51             if ( dfn[v] < low[u] )

52             {

53                 low[u] = dfn[v];

54             }

55         }

56     }

57     if ( low[u] == dfn[u] )

58     {

59         cnt++;

60         while ( 1 )

61         {

62             int tmp = s.top(); s.pop();

63             inStack[tmp] = false;

64             if ( tmp == u ) break;

65         }

66     }

67 }

68 

69 void solve()

70 {

71     for ( int i = 1; i <= n; i++ )

72     {

73         if ( !dfn[i] )

74         {

75             dfs(i);

76         }

77     }

78 }

79 

80 int main ()

81 {

82     while ( scanf("%d%d", &n, &m), n + m )

83     {

84         int u, v;

85         init();

86         while ( m-- )

87         {

88             scanf("%d%d", &u, &v);

89             addEdge( u, v );

90         }

91         solve();

92         printf("%s\n", ( cnt == 1 ) ? "Yes" : "No");

93     }

94     return 0;

95 }

你可能感兴趣的:(tar)