fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. const int NMAX = 15;
  6.  
  7. struct node {
  8. int info;
  9. node* next;
  10. };
  11.  
  12. node* G[NMAX];
  13. node* Gt[NMAX];
  14.  
  15. void add(node* &first, int val) {
  16. node* p = new node;
  17. p -> info = val;
  18. p -> next = first;
  19. first = p;
  20. }
  21.  
  22. void read(int& n, int& m) {
  23. cin >> n >> m;
  24. for (int i = 1; i <= m; ++ i) {
  25. int x, y;
  26. cin >> x >> y;
  27. add(G[x], y);
  28. add(Gt[y], x);
  29. }
  30. }
  31.  
  32. void dfs1(int currNode, bool seen[NMAX], int stck[NMAX], int& dim) {
  33. seen[currNode] = true;
  34. for (node* p = G[currNode]; p; p = p -> next)
  35. if (!seen[p -> info])
  36. dfs1(p -> info, seen, stck, dim);
  37. stck[++ dim] = currNode;
  38. }
  39.  
  40. void dfs2(int currNode, bool seen[NMAX], int idx) {
  41. seen[currNode] = true;
  42. // prelucrare nodul cnt din componenta idx
  43. cout << currNode << " ";
  44. for (node* p = Gt[currNode]; p; p = p -> next)
  45. if (!seen[p -> info])
  46. dfs2(p -> info, seen, idx);
  47. }
  48.  
  49. void solve(int n) {
  50. bool seen[NMAX];
  51. int stck[NMAX], dim = 0;
  52. for (int i = 1; i <= n; ++ i)
  53. seen[i] = false;
  54. for (int i = 1; i <= n; ++ i)
  55. if (!seen[i])
  56. dfs1(i, seen, stck, dim);
  57.  
  58. int idx = 0;
  59. for (int i = 1; i <= n; ++ i)
  60. seen[i] = false;
  61. while (dim) {
  62. if (!seen[stck[dim]]) {
  63. ++ idx;
  64. cout << idx << " ";
  65. dfs2(stck[dim], seen, idx);
  66. cout << "\n";
  67. }
  68. -- dim;
  69. }
  70. }
  71.  
  72. int main() {
  73. int n, m;
  74. read(n, m);
  75. solve(n);
  76. return 0;
  77. }
  78.  
Success #stdin #stdout 0s 4540KB
stdin
6 7
1 2
2 1
2 3
3 4
4 5
5 6
6 4
stdout
1 1 2 
2 3 
3 4 6 5