fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. int main() {
  5.  
  6. int n;
  7. cin>>n;
  8. int e;
  9. cin>>e;
  10.  
  11. vector<int> g[n+1];
  12.  
  13. for(int i=1; i<=e; i++){
  14. int u,v;
  15. cin>>u;
  16. cin>>v;
  17. g[u].push_back(v);
  18. g[v].push_back(u);
  19. }
  20.  
  21. int source;
  22. cin>>source;
  23.  
  24. // solution;
  25.  
  26. queue<int> q;
  27.  
  28. q.push(source);
  29.  
  30. vector<int> record (n+1,-1);
  31. record[source]=0;
  32. int level = 1;
  33. while(!q.empty()){
  34.  
  35. int t = q.front();
  36.  
  37. q.pop();
  38.  
  39. for(auto x: g[t]){
  40.  
  41. if(record[x]<0){
  42. q.push(x);
  43. record[x] = record[t]+1;
  44. }
  45. }
  46. level++;
  47.  
  48. }
  49.  
  50. for(int i=1; i<=n; i++){
  51. cout<< record[i]<< " ";
  52. }
  53.  
  54. return 0;
  55. }
Success #stdin #stdout 0.01s 5288KB
stdin
5 4
1 2
2 3
2 4
3 5
2
stdout
1 0 1 1 2