fork download
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int N = 1000005;
  6.  
  7. int n, m, Distance[N];
  8. vector<int> dsk[N];
  9. bool dd[N];
  10.  
  11. void bfs(int u) {
  12. queue<int> Q;
  13. Q.push(u);
  14. Distance[u] = 0;
  15. dd[u] = true;
  16.  
  17. while (Q.size()) {
  18. int u = Q.front();
  19. Q.pop();
  20.  
  21. /// keo u di
  22. /// dan toi bfs() toi duoc
  23. /// cung bi keo di
  24. for (int v : dsk[u])
  25. if (dd[v] == false) {
  26. dd[v] = true;
  27. Distance[v] = Distance[u] + 1;
  28. Q.push(v);
  29. }
  30. }
  31. }
  32.  
  33. int main() {
  34. // freopen("test.inp", "r", stdin);
  35. // freopen("test.out", "w", stdout);
  36. int s;
  37. cin >> n >> m >> s;
  38. for (int i = 1; i <= m; i++) {
  39. int u, v;
  40. cin >> u >> v;
  41. dsk[u].push_back(v);
  42. dsk[v].push_back(u);
  43. }
  44.  
  45. bfs(s);
  46. /// trong so, gia tri dinh
  47.  
  48. /// a[i].first = a[j].first
  49.  
  50. /// so sanh a[i].second, a[j].second
  51.  
  52. vector<pair<int, int>> V;
  53.  
  54. for (int i = 1; i <= n; i++)
  55. if (dd[i])
  56. V.push_back({Distance[i], i});
  57.  
  58. sort(V.begin(), V.end());
  59.  
  60. for (pair<int, int> v : V)
  61. cout << v.second << " " << v.first << endl;
  62. }
  63.  
  64.  
  65.  
Success #stdin #stdout 0.01s 28196KB
stdin
Standard input is empty
stdout
Standard output is empty