fork(3) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <stack>
  4.  
  5. int n;
  6.  
  7. using namespace std;
  8. vector <int> graph[1000006];
  9. int components[1000006];
  10. int no_of_components;
  11. stack <int> mystack;
  12.  
  13. int main(){
  14.  
  15. // Load the graph
  16.  
  17. cin >> n;
  18. for (int i=0; i<n; i++){
  19. int X;
  20. cin >> X;
  21. graph[X-1].push_back(i);
  22. }
  23.  
  24. // Display loaded graph
  25. cout<<"Graph:"<<endl;
  26. for (int i=0; i<n; i++) {
  27. cout << "Node "<<i<<" --> ";
  28. for (auto &x : graph[i])
  29. cout<< x<< " ";
  30. cout<<endl;
  31. }
  32. cout<<endl;
  33.  
  34. // Identify the connectect groups
  35.  
  36. for (int i=0; i<n; i++){
  37.  
  38. if (components[i]>0)
  39. continue;
  40.  
  41. no_of_components++;
  42.  
  43. mystack.push(i);
  44. components[i]=no_of_components;
  45.  
  46. while (mystack.empty()==false){
  47. int v;
  48.  
  49. v=mystack.top();
  50. mystack.pop();
  51.  
  52. for (int u=0; u<graph[v].size(); u++){
  53. if (components[graph[v][u]]>0) continue;
  54.  
  55. mystack.push(graph[v][u]);
  56. components[graph[v][u]]=no_of_components;
  57.  
  58. }
  59. }
  60. }
  61.  
  62. // Display resutls
  63.  
  64. cout << "Number of connected components: "<<no_of_components<<endl;
  65. for (int i=0;i<n; i++)
  66. cout <<"Node "<< i<<" is in component "<<components[i]<<endl;
  67.  
  68. return 0;
  69.  
  70. }
Success #stdin #stdout 0s 19048KB
stdin
4 2 1 2 4
stdout
Graph:
Node 0 --> 1 
Node 1 --> 0 2 
Node 2 --> 
Node 3 --> 3 

Number of connected components: 2
Node 0 is in component 1
Node 1 is in component 1
Node 2 is in component 1
Node 3 is in component 2