nrk009

Longest Path in Tree/Diameter of a tree

Mar 9th, 2020 (edited)
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL)
  5. #define ll long long
  6. #define ld long double
  7. #define pb push_back
  8. #define fe first
  9. #define se second
  10. #define nl "\n"
  11. #define pp pair < ll , ll >
  12. #define sz(x) (ll)x.size()
  13. #define st(x) sort(x.begin(),x.end())
  14. #define rst(x) sort(x.rbegin(), x.rend())
  15. #define all(x) x.begin(),x.end()
  16. long double pi = 3.14159265358979323;
  17.  
  18. const double EPS = 1e-12;
  19. const int N = 1e6 + 5;
  20. const int mod = 1e9 + 7;
  21.  
  22. bool vis[N];
  23. vector < ll > v[N];
  24. ll dp[N];
  25. //Diameter of a tree
  26. ll ans;
  27. void dfs(ll s){
  28.  
  29.     vis[s] = 1;
  30.     for(auto it : v[s]){
  31.         if(!vis[it]){
  32.             dfs(it);
  33.         }
  34.     }
  35.    
  36.     multiset < ll  > st;
  37.     st.insert(0);
  38.     for(auto it : v[s])st.insert(dp[it]);
  39.     auto itr = st.rbegin();
  40.     dp[s] = 1 + *itr;
  41.     //cout << dp[s] << " ";
  42.     if(st.size() > 1){
  43.         itr++;
  44.         ans = max(ans,  dp[s] + *itr);
  45.     }
  46.     ans = max(ans , dp[s]);
  47.         //cout << s << " " << dp[s] << "\n";
  48. }
  49.  
  50.  
  51. int main()
  52. {
  53.     fast;
  54.     ll n, m;
  55.     cin >> n >> m ;
  56.     for(int i = 0 ; i < m ;i++ ){
  57.           ll a , b;
  58.           cin >> a >> b ;
  59.           v[a].pb(b);
  60.           v[b].pb(a);
  61.     }
  62.     dfs(1);
  63.     cout << ans - 1;
  64.  
  65.    
  66.  
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83.  
  84.  
  85.  
  86.  
  87.    
  88.     return 0;
  89.    
  90. }
Add Comment
Please, Sign In to add comment