fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long int
  4. #define double long double
  5.  
  6.  
  7. const int M = 1000000007;
  8. const int N = 3e5+9;
  9. const int INF = 2e9+1;
  10. const int MAXN = 100000;
  11. const int LINF = 2000000000000000001;
  12.  
  13. //_ ***************************** START Below *******************************
  14.  
  15.  
  16.  
  17. //* Child BFS :
  18. //* Visited marked in child
  19. //* Each Node visited once only i.e. queue contains distinct
  20.  
  21. //* 1
  22. //* / \
  23. //* 2 5
  24. //* | |
  25. //* 3 ------ 4
  26. //* 4 is 1st explored by 5 and put in queue (visited)
  27. //* lvl[4] = 2
  28.  
  29. //* 4 can't be explored by 3 (already visited yet)
  30.  
  31.  
  32. vector<vector<int>> graph;
  33. void consistency(int n, int m){
  34.  
  35. queue<int> q;
  36. q.push(1);
  37. vector<int> visited(n+1, false);
  38. visited[1] = true;
  39.  
  40. vector<int> levels(n+1, 0);
  41.  
  42. while(!q.empty()){
  43. auto node = q.front(); q.pop();
  44.  
  45. for(int ch : graph[node]){
  46. if(visited[ch]) continue;
  47.  
  48. q.push(ch);
  49. levels[ch] = levels[node] + 1;
  50. visited[ch] = true;
  51. }
  52.  
  53.  
  54. }
  55.  
  56. for(int i=1; i<=n; i++){
  57. cout << levels[i] << " ";
  58. }cout << endl;
  59.  
  60.  
  61. }
  62.  
  63.  
  64.  
  65. void solve() {
  66.  
  67. int n, m;
  68. cin >> n >> m;
  69.  
  70. graph.resize(n+1); // 1 based indexing
  71. for(int i=0; i<m; i++){
  72. int x, y;
  73. cin >> x >> y;
  74. graph[x].push_back(y);
  75. graph[y].push_back(x);
  76. }
  77.  
  78. consistency(n, m);
  79.  
  80.  
  81. }
  82.  
  83.  
  84.  
  85.  
  86.  
  87. int32_t main() {
  88. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  89.  
  90. int t = 1;
  91. while (t--) {
  92. solve();
  93. }
  94.  
  95. return 0;
  96. }
Success #stdin #stdout 0.01s 5308KB
stdin
5 5
1 2
1 5
2 3
5 4
3 4
stdout
0 1 2 2 1