fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. const int maxn = 1001;
  4. int n;
  5. int d[maxn];
  6. bool visited[maxn];
  7. vector<int> ke[1001];
  8. void inp(){
  9. cin >> n ;
  10. for(int i = 1 ; i <= n - 1 ; i ++){
  11. int x,y;
  12. cin >> x >> y;
  13. ke[x].push_back(y);
  14. ke[y].push_back(x);
  15. }
  16. }
  17. void BFS(int u){
  18. visited[u] = true;
  19. queue<int> q;
  20. q.push(u);
  21. d[u] = 0;
  22. while(!q.empty()){
  23. int p = q.front();
  24. q.pop();
  25. for(int x : ke[p]){
  26. if(!visited[x]){
  27. d[x] = d[p] + 1;
  28. visited[x] = true;
  29. q.push(x);
  30. }
  31. }
  32. }
  33. }
  34. int main(){
  35. inp();
  36. BFS(1);
  37. for(int i = 1 ; i <= n ; i++){
  38. cout << d[i] << " ";
  39. }
  40. }
Success #stdin #stdout 0.01s 5304KB
stdin
7
1 2
2 3
3 4
1 5
5 6
1 7
stdout
0 1 2 3 1 2 1