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. vector<vector<int>> graph;
  17. void consistency(int n, int m){
  18.  
  19. queue<int> q;
  20. q.push(1);
  21. vector<int> visited(n+1, false);
  22. visited[1] = true;
  23.  
  24. while(!q.empty()){
  25. int sz = q.size();
  26. for(int i=0; i<sz; i++){
  27. auto node = q.front(); q.pop();
  28.  
  29. for(int ch : graph[node]){
  30. if(visited[ch]) continue;
  31.  
  32. q.push(ch);
  33. visited[ch] = true;
  34. }
  35.  
  36. }
  37.  
  38. }
  39.  
  40. for(int i=1; i<=n; i++){
  41. cout << visited[i] << " ";
  42. }cout << endl;
  43.  
  44.  
  45. }
  46.  
  47.  
  48.  
  49. void solve() {
  50.  
  51. int n, m;
  52. cin >> n >> m;
  53.  
  54. graph.resize(n+1); // 1 based indexing
  55. for(int i=0; i<m; i++){
  56. int x, y;
  57. cin >> x >> y;
  58. graph[x].push_back(y);
  59. graph[y].push_back(x);
  60. }
  61.  
  62. consistency(n, m);
  63.  
  64.  
  65. }
  66.  
  67.  
  68.  
  69.  
  70.  
  71. int32_t main() {
  72. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  73.  
  74. int t = 1;
  75. while (t--) {
  76. solve();
  77. }
  78.  
  79. return 0;
  80. }
Success #stdin #stdout 0.01s 5320KB
stdin
5 3
1 2
1 3
1 4
stdout
1 1 1 1 0