fork download
  1. #include<iostream>
  2. #include<vector>
  3. #include<cstring>
  4. #include<stack>
  5. #include<cstdio>
  6.  
  7. #define max 1000
  8. #define INF 100000000
  9. using namespace std;
  10.  
  11. vector<int> adj[max];
  12. int s[max],f[max],nodes[max];
  13. int time_count,n,e;
  14. char visited[max];
  15. stack<int> st;
  16. int tim,m=0;
  17.  
  18. void createAdjecenyList(int u,int v){
  19. adj[u].push_back(v);
  20. adj[v].push_back(u);
  21. }
  22.  
  23. void print_st(stack<int> ps){
  24. while(!ps.empty()){
  25. printf("%d ",ps.top());
  26. ps.pop();
  27. }
  28. printf("\n");
  29. }
  30.  
  31. void printnodes(){
  32. int i;
  33. for(i=0;i<m;i++)
  34. printf("node: %d st_time: %d end_time: %d\n",nodes[i],s[nodes[i]],f[nodes[i]]);
  35. }
  36.  
  37. void dfs(int v){
  38. int u,i,count;
  39. tim = 0;
  40. st.push(v);
  41. visited[v]=1;
  42. while(!st.empty()){
  43. u = st.top();
  44. count=0;
  45. s[u] = tim++;
  46. printf("Printing stack\n");
  47. print_st(st);
  48. nodes[m++]=u;
  49. for(i=0;i<adj[u].size();i++)
  50. if(!visited[adj[u][i]]) {
  51. st.push(adj[u][i]);
  52. visited[adj[u][i]] = 1;
  53. }
  54. else count++;
  55. if(count==adj[u].size()){
  56. f[u]=tim++;
  57. st.pop();
  58. }
  59. }
  60. }
  61.  
  62. int main(){
  63. int u,v,i;
  64. memset(visited,0,sizeof(visited)); // 0 is for new node and 1 is for visited node
  65. scanf("%d",&n); // number of nodes
  66. scanf("%d",&e); // number of edges
  67. while(e--) {
  68. scanf("%d %d",&u,&v);
  69. createAdjecenyList(u,v);
  70. }
  71. dfs(1);
  72. printnodes();
  73. cout<<endl;
  74. return 0;
  75. }
Success #stdin #stdout 0s 3504KB
stdin
6
8
1 2
2 3
1 3
1 4
2 4
2 5
3 5
3 6
stdout
Printing stack
1  
Printing stack
4  3  2  1  
Printing stack
3  2  1  
Printing stack
6  5  3  2  1  
Printing stack
5  3  2  1  
Printing stack
3  2  1  
Printing stack
2  1  
Printing stack
1  
node: 1   st_time: 12   end_time: 13
node: 4   st_time: 1   end_time: 2
node: 3   st_time: 8   end_time: 9
node: 6   st_time: 4   end_time: 5
node: 5   st_time: 6   end_time: 7
node: 3   st_time: 8   end_time: 9
node: 2   st_time: 10   end_time: 11
node: 1   st_time: 12   end_time: 13