Advertisement
tepyotin2

TreeDistanceI

May 18th, 2025
571
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. struct Node{
  6.     vector<int> links;
  7.     int depth;
  8. };
  9.  
  10. int n;
  11. vector<Node> tree;
  12. vector<bool> visited;
  13. int mxd;
  14. int mxn;
  15. vector<int> dist;
  16.  
  17. void findDepth(int node){
  18.     visited[node] = true;
  19.     //cout << node << ", " << tree[node].depth << '\n';
  20.     //cout << tree[node].depth << '\n';
  21.     for(auto child: tree[node].links){
  22.         if(!visited[child]){
  23.             tree[child].depth = tree[node].depth+1;
  24.             dist[child] = max(dist[child], tree[child].depth);
  25.             if(tree[child].depth>mxd){
  26.                 mxd = tree[child].depth;
  27.                 mxn = child;
  28.             }
  29.             findDepth(child);
  30.         }
  31.     }
  32. }
  33.  
  34. int main(){
  35.     //freopen("treedistances.in", "r", stdin);
  36.    
  37.     cin >> n;
  38.     tree.resize(n+1);
  39.     visited.resize(n+1);
  40.     dist.resize(n+1);
  41.     int a, b;
  42.     while(cin >> a){
  43.         cin >> b;
  44.         tree[a].links.push_back(b);
  45.         tree[b].links.push_back(a);
  46.     }
  47.     findDepth(1);
  48.     fill(visited.begin(), visited.end(), false);
  49.     //cout << "==========" << '\n';
  50.     mxd = 0;
  51.     tree[mxn].depth = 0;
  52.     findDepth(mxn);
  53.     //cout << mxd << '\n';
  54.     fill(visited.begin(), visited.end(), false);
  55.     tree[mxn].depth = 0;
  56.     findDepth(mxn);
  57.     for(int i=1; i<=n; i++){
  58.         cout << dist[i] << '\n';
  59.     }
  60.      
  61.     return 0;
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement