fork download
  1. //C++ implementation of Tarjan Algorithm
  2. #include<cstdio>
  3. #include<cstring>
  4. #include<iostream>
  5. #include<vector>
  6. #include<stack>
  7. #include<cstdlib>
  8. #include<algorithm>
  9. using namespace std;
  10. #define MAX 2003
  11. stack<int>st;
  12. bool stacked[MAX];
  13. vector<vector<int> >G(MAX);
  14. int low[MAX],disc[MAX],c=0;
  15. void tarzan(int u)
  16. {
  17. static int timer=0;
  18. disc[u]=low[u]=++timer;
  19. st.push(u);
  20. stacked[u]=true;
  21. for(int i=0;i<G[u].size();i++)
  22. {
  23. int v=G[u][i];
  24. if(disc[v]==-1)
  25. {
  26. tarzan(v);
  27. low[u]=min(low[u],low[v]);
  28. }
  29. else if(stacked[v])
  30. {
  31. low[u]=min(low[u],disc[v]);
  32. }
  33. }
  34. int w=0;
  35. if(low[u]==disc[u])
  36. {
  37. c++;
  38. while(st.top()!=u)
  39. {
  40. stacked[w]=false;
  41. st.pop();
  42. }
  43. w=st.top();
  44. stacked[w]=false;
  45. st.pop();
  46. }
  47. }
  48. int main()
  49. {
  50. int m,n;
  51. cin>>n>>m;
  52. while(m|n)
  53. {
  54. for(int i=1;i<=m;i++)
  55. {
  56. int x,y,k;
  57. cin>>x>>y>>k;
  58. if(k==1)
  59. G[x].push_back(y);
  60. else
  61. {
  62. G[x].push_back(y);
  63. G[y].push_back(x);
  64. }
  65. }
  66. c=0;
  67. memset(disc,-1,sizeof disc);
  68. memset(stacked,false,sizeof stacked);
  69. memset(low,-1,sizeof low);
  70. for(int i=1;i<=n;i++)
  71. {
  72. if(disc[i]==-1)
  73. tarzan(i);
  74. }
  75. (c==1)?cout<<"1\n":cout<<"0\n";
  76. cin>>n>>m;
  77. for(int i=1;i<=n;i++)
  78. G[i].clear();
  79. }
  80. }
Success #stdin #stdout 0s 2884KB
stdin
4 5
1 2 1
1 3 2
2 4 1
3 4 1
4 1 2
3 2
1 2 2
1 3 2
3 2
1 2 2
1 3 1
4 2
1 2 2
3 4 2
0 0
stdout
1
1
0
0