fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const long long MaxN = 1e6 + 5;
  5.  
  6. long long n;
  7. vector<long long> a[MaxN];
  8. bool visited[MaxN];
  9. long long depth[MaxN];
  10.  
  11. void input()
  12. {
  13. cin >> n;
  14.  
  15. for (long long i = 1; i <= n - 1; i++)
  16. {
  17. long long u, v;
  18. cin >> u >> v;
  19.  
  20. a[u].push_back(v);
  21. a[v].push_back(u);
  22. }
  23. }
  24.  
  25. void dfs(long long s)
  26. {
  27. stack<long long> st;
  28.  
  29. st.push(s);
  30. visited[s] = true;
  31. depth[s] = 0;
  32.  
  33. while (!st.empty())
  34. {
  35. long long u = st.top();
  36. st.pop();
  37.  
  38. for (long long v : a[u])
  39. {
  40. if (!visited[v])
  41. {
  42. visited[v] = true;
  43. depth[v] = depth[u] + 1;
  44. st.push(v);
  45. }
  46. }
  47. }
  48. }
  49.  
  50. void solve()
  51. {
  52. dfs(1);
  53.  
  54. for (long long i = 1; i <= n; i++)
  55. {
  56. cout << depth[i] << " ";
  57. }
  58. }
  59.  
  60. int main()
  61. {
  62. input();
  63. solve();
  64. }
Success #stdin #stdout 0.01s 29952KB
stdin
Standard input is empty
stdout
Standard output is empty