fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. vector<int> height(1e5+7);
  4.  
  5. void DFS(int node, vector<vector<int>>& g, vector<int>& visited, vector<int>& parent){
  6.  
  7. visited[node] = 1;
  8. int h = 0;
  9. for (auto &i : g[node]){
  10. if(visited[i] == 0){
  11. parent[i] = node;
  12. DFS(i, g, visited, parent);
  13. }
  14. }
  15.  
  16. for (auto child : g[node]){
  17. if(child != parent[node]){
  18. h = max(h, height[child]);
  19. }
  20. }
  21.  
  22. height[node] = h+1;
  23. }
  24.  
  25. int main() {
  26.  
  27. int n,e;
  28. cin >> n >> e;
  29.  
  30. vector<vector<int>> g(n+5);
  31.  
  32. for (int i = 0; i < e; i++){
  33. int a, b;
  34. cin >> a >> b;
  35. g[a].push_back(b);
  36. g[b].push_back(a);
  37. }
  38.  
  39. int source;
  40. cin >> source;
  41.  
  42. vector<int> visited(n+5, 0);
  43. vector<int> parent(n+5, 0);
  44.  
  45. DFS(source, g, visited, parent);
  46.  
  47. for (int i = 1; i <= n; i++){
  48. cout << height[i] << " ";
  49. }
  50.  
  51. return 0;
  52. }
Success #stdin #stdout 0.01s 5316KB
stdin
7 6
1 2
1 7
1 5
2 3
2 4
5 6
1
stdout
3 2 1 1 2 1 1