fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int m,n;
  5.  
  6. void dfs1(vector<int>*g,int u,stack<int>&s,vector<int>&vis)
  7. {
  8.  
  9. vis[u]=1;
  10. for(int x:g[u])
  11. {
  12. if(vis[x]==1) continue;
  13. dfs1(g,x,s,vis);
  14. }
  15. vis[u]=2;
  16. s.push(u);
  17. }
  18.  
  19. void dfs2(vector<int>*g,int u,vector<int>&vis,vector<int>&scc)
  20. {
  21.  
  22. vis[u]=1;
  23. scc.push_back(u);
  24. for(int x:g[u])
  25. {
  26. if(vis[x]==1) continue;
  27. dfs2(g,x,vis,scc);
  28. }
  29. vis[u]=2;
  30.  
  31. }
  32.  
  33. int main()
  34. {
  35. cin>>n>>m;
  36. vector<int>g1[n+1],g2[n+1];
  37.  
  38. for(int i=0;i<m;i++)
  39. {
  40. int u,v;
  41. cin>>u>>v;
  42.  
  43. g1[u].push_back(v);
  44. g2[v].push_back(u);
  45. }
  46.  
  47. stack<int>s;
  48. vector<int>vis(n+1,0);
  49. for(int i=1;i<=n;i++)
  50. {
  51. if(vis[i]==0)
  52. {
  53. dfs1(g1,i,s,vis);
  54. }
  55. }
  56. vector<int>vis2(n+1,0);
  57. vector<vector<int>>allscc;
  58. while(!s.empty())
  59.  
  60. {
  61. int cur=s.top();
  62. s.pop();
  63. if(vis2[cur]==0)
  64. {
  65. vector<int>scc;
  66. dfs2(g2,cur,vis2,scc);
  67. allscc.push_back(scc);
  68. }
  69. }
  70. for(auto x: allscc)
  71. {
  72. for(int u:x)
  73. {
  74. cout<<u<< " ";
  75. }
  76. cout<<endl;
  77. }
  78.  
  79. }
  80. /*
  81.  
  82. 8 14
  83. 1 2
  84. 2 3
  85. 3 1
  86. 3 4
  87. 2 4
  88. 2 5
  89. 4 6
  90. 6 4
  91. 5 7
  92. 7 5
  93. 5 6
  94. 6 8
  95. 7 8
  96. 8 8
  97. */
  98.  
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Standard output is empty