fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <string>
  5. #include <cmath> //12605 5 3
  6. #include <queue>
  7. #include <numeric>
  8. #include <set>
  9. using namespace std;
  10. int visitb[1001]={0,};
  11. int visitd[1001]={0,};
  12. vector<int>graph[1001];
  13. int bfscount[1001];
  14. int cntbfs=1;
  15. int dfscount[1001];
  16. int cntdfs=1;
  17. void dfs(int x){
  18. visitd[x] =1;
  19. dfscount[cntdfs]=x;
  20. cntdfs++;
  21. for(int i=0; i<graph[x].size(); i++){
  22. int y = graph[x][i];
  23. if(!visitd[y]){
  24. dfs(y);
  25. }
  26. }
  27. }
  28. void bfs(int start){
  29. queue<int>q;
  30. visitb[start]=1;
  31. q.push(start);
  32. while(!q.empty()){
  33. int x=q.front();
  34. bfscount[cntbfs]=x;
  35. cntbfs++;
  36. q.pop();
  37. for(int i=0; i<graph[x].size(); i++){
  38. int y=graph[x][i];
  39. if(!visitb[y]){
  40. q.push(y);
  41. visitb[y]=1;
  42. }
  43.  
  44. }
  45. }
  46. }
  47. int main(){
  48. ios::sync_with_stdio(false);
  49. cin.tie(NULL);
  50. int n,m,v;
  51. cin>>n>>m>>v;
  52. for(int i=0; i<m; i++){
  53. int x,y;
  54. cin>>x>>y;
  55. graph[x].push_back(y);
  56. graph[y].push_back(x);
  57. }
  58. for (int i=0;i<n;i++){
  59. sort(graph[i].begin(),graph[i].end());
  60. }
  61. bfs(v);
  62. dfs(v);
  63. for(int i=1; i<=n; i++){
  64. if(bfscount[i]!=0){
  65. cout<<dfscount[i]<<" ";
  66. }
  67.  
  68. }
  69. cout<<"\n";
  70. for(int i=1; i<=n; i++){
  71. if(bfscount[i]!=0){
  72. cout<<bfscount[i]<<" ";
  73. }
  74.  
  75. }
  76.  
  77. return 0;
  78. }
Success #stdin #stdout 0.01s 5308KB
stdin
1000 3 1000
1000 3
1000 2
1000 1
stdout
1000 3 2 1 
1000 3 2 1