fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. static const int N = 200005;
  5. vector<int> adj[N];
  6.  
  7. int visited[N], level[N];
  8. vector<pair<int,int>>v;
  9.  
  10. bool cmp(pair<int,int>a, pair<int,int>b)
  11. {
  12. return a.second>b.second;
  13. }
  14.  
  15. void dfs(int node)
  16. {
  17. visited[node] = 1;
  18.  
  19. for(auto x:adj[node])
  20. {
  21. if(visited[x]==0)
  22. {
  23. level[x] = level[node]+1;
  24. v.push_back({x,level[x]});
  25. dfs(x);
  26. }
  27. }
  28.  
  29. return;
  30. }
  31.  
  32.  
  33. int main() {
  34.  
  35. int n; cin >> n;
  36.  
  37. if(n==1) { cout<<0<<endl; return 0; }
  38.  
  39. for(int i=1; i<n; i++)
  40. {
  41. int u,v; cin >> u >> v;
  42. adj[u].push_back(v);
  43. adj[v].push_back(u);
  44. }
  45.  
  46. dfs(1);
  47.  
  48. sort(v.begin(),v.end(),cmp);
  49.  
  50. int x = v[0].first;
  51. v.clear();
  52.  
  53. for(int i=0; i<N; i++) { visited[i]=0; level[i]=0; }
  54.  
  55. dfs(x);
  56.  
  57. sort(v.begin(),v.end(),cmp);
  58.  
  59. int ans = v[0].second;
  60.  
  61. cout<<ans<<endl;
  62.  
  63. return 0;
  64. }
  65.  
Success #stdin #stdout 0.01s 9872KB
stdin
5
1 2
1 3
3 4
3 5
stdout
3