fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. using ll = long long;
  4.  
  5. const int MAXN=2E5+1;
  6. vector<ll>g[MAXN];
  7. vector<ll>dis(MAXN,0);
  8.  
  9. void dfs(int node,int par){
  10. for(auto &c:g[node]){
  11. if(c != par){
  12. dis[c]=dis[node]+1;
  13. dfs(c,node);
  14. }
  15. }
  16. }
  17.  
  18. void _144()
  19. {
  20. ll n;
  21. cin>>n;
  22.  
  23. for(int i=1;i<=n-1;i++){
  24. ll u,v;
  25. cin>>u>>v;
  26.  
  27. g[u].push_back(v);
  28. g[v].push_back(u);
  29. }
  30.  
  31. dfs(1,-1);
  32.  
  33. ll firstFarthestNode=-1;
  34. ll maxi=0;
  35. for(int i=1;i<=n;i++){
  36. if(dis[i]>maxi){
  37. maxi=dis[i];
  38. firstFarthestNode=i;
  39. }
  40. }
  41.  
  42. dis.assign(n+1,0);
  43. dfs(firstFarthestNode,-1);
  44.  
  45. maxi=0;
  46. for(int i=1;i<=n;i++){
  47. if(dis[i]>maxi){
  48. maxi=dis[i];
  49. }
  50. }
  51.  
  52. ll diameter=maxi;
  53. cout<<diameter;
  54. return;
  55. }
  56.  
  57.  
  58. int main() {
  59. ios::sync_with_stdio(false);
  60. cin.tie(nullptr);
  61.  
  62. int t=1;
  63. // cin >> t;
  64.  
  65. while (t--) _144();
  66. return 0;
  67. }
Runtime error #stdin #stdout 0.02s 9708KB
stdin
Standard input is empty
stdout
Standard output is empty