Advertisement
Saleh127

CSES 1131 / DFS - Tree diameter

Apr 8th, 2022
886
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.81 KB | None | 0 0
  1. /***
  2.  created: 2022-04-08-13.54.44
  3. ***/
  4.  
  5. #include <bits/stdc++.h>
  6. using namespace std;
  7. #define ll long long
  8. #define test int tt; cin>>tt; for(int cs=1;cs<=tt;cs++)
  9. #define get_lost_idiot return 0
  10. #define nl '\n'
  11.  
  12. vector<ll>g[200005];
  13. bool v[200005];
  14. ll ans=0,cc=0,node;
  15.  
  16. void dfs(ll c,ll p,ll d)
  17. {
  18.     for(auto dd:g[c])
  19.     {
  20.         if(dd!=p)
  21.         {
  22.             dfs(dd,c,d+1);
  23.         }
  24.     }
  25.     if(d>ans)
  26.     {
  27.         ans=d;
  28.         node=c;
  29.     }
  30. }
  31.  
  32. int main()
  33. {
  34.     ios_base::sync_with_stdio(0);
  35.     cin.tie(0);
  36.     cout.tie(0);
  37.  
  38.     ll n,m,i,j,k,l;
  39.  
  40.     cin>>n;
  41.  
  42.     for(i=0;i<n-1;i++)
  43.     {
  44.         cin>>j>>k;
  45.  
  46.         g[j].push_back(k);
  47.         g[k].push_back(j);
  48.     }
  49.  
  50.  
  51.     dfs(1,0,0);
  52.  
  53.     cc=0;
  54.  
  55.     dfs(node,0,0);
  56.  
  57.     cout<<ans<<nl;
  58.  
  59.     get_lost_idiot;
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement