Advertisement
a53

PARCURGERE_GRAFURI

a53
Feb 3rd, 2020
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. /// DFS
  2. /// ========
  3. /// https://www.infoarena.ro/job_detail/2535791?action=view-source
  4. #include <iostream>
  5. #include <fstream>
  6. #include <vector>
  7. #define MAX 100001
  8. using namespace std;
  9. ifstream ci ("dfs.in");
  10. ofstream co ("dfs.out");
  11. vector<int>NOD[MAX];
  12. bool viz[MAX];
  13. int n,m;
  14. int x,y;
  15. void DFS (int x)
  16. {
  17. viz[x]=true;
  18. for (unsigned int i=0;i<NOD[x].size();++i)
  19. {
  20. if (viz[NOD[x][i]]==false)
  21. {
  22. DFS(NOD[x][i]);
  23. }
  24. }
  25. }
  26. int main ()
  27. {
  28. ci>>n>>m;
  29. while (m)
  30. {
  31. m--;
  32. ci>>x>>y;
  33. NOD[x].push_back(y);
  34. NOD[y].push_back(x);
  35. }
  36.  
  37. int temp=0;
  38. for (int i=1;i<=n;++i)
  39. {
  40. // temp++;
  41. if (viz[i]==false)
  42. {
  43. temp++;
  44. DFS(i);
  45. }
  46. }
  47. co<<temp;
  48. return 0;
  49. }
  50. /// BFS
  51. /// ================
  52. #include <bits/stdc++.h>
  53. /// https://www.infoarena.ro/job_detail/2537114?action=view-source
  54. using namespace std;
  55.  
  56. const int MAX = 100001;
  57.  
  58. vector <int> nod[MAX];
  59. deque <int> coada;
  60. int viz[MAX], n, m, s, lung[MAX];
  61.  
  62. ifstream in ("bfs.in");
  63. ofstream out ("bfs.out");
  64.  
  65. int BFS()
  66. {
  67. int x;
  68. coada.push_back(s);
  69. viz[s] = 1;
  70. lung[s] = 0;
  71. while(!coada.empty())
  72. {
  73. x = coada.front();
  74. coada.pop_front();
  75. for(int i = 0; i < nod[x].size(); i++)
  76. {
  77. if(!viz[nod[x][i]])
  78. {
  79. coada.push_back(nod[x][i]);
  80. lung[nod[x][i]] = lung[x] + 1;
  81. viz[nod[x][i]] = 1;
  82. }
  83. }
  84. }
  85. }
  86.  
  87. int main()
  88. {
  89. int x, y;
  90. in >> n >> m >> s;
  91. while(m)
  92. {
  93. m--;
  94. in >> x >> y;
  95. nod[x].push_back(y);
  96. }
  97. for(int i = 1; i <= n; i++)
  98. {
  99. lung[i] = -1;
  100. }
  101. BFS();
  102. for(int i = 1; i <= n; i++)
  103. {
  104. out << lung[i] << " ";
  105. }
  106. return 0;
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement