fork download
  1. #include <bits/stdc++.h>
  2. #include <iomanip>
  3. #include <ext/pb_ds/assoc_container.hpp>
  4. #include <ext/pb_ds/tree_policy.hpp>
  5. using namespace __gnu_pbds;
  6. #define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>
  7. using namespace std;
  8. #define ll long long
  9. #define pb push_back
  10. #define all(a) a.begin(),a.end()
  11. #define death ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
  12.  
  13. ////////////////////////////////////global variables//////////////////////////////////////////////////
  14. map<int ,vector<int>> adj;
  15. map<int, bool> vis;
  16. int farLeaf;
  17. int maxdis;
  18. ////////////////////////////////////recursion/////////////////////////////////////////////////////////
  19.  
  20. /////////////////////////////////////functions///////////////////////////////////////////////////////
  21. bool isLeaf(int node) {
  22. return adj[node].size() == 1;
  23. }
  24. void dfs(ll num,int dis){
  25. if (maxdis < dis) {
  26. maxdis = dis;
  27. farLeaf=num;
  28. }
  29. vis[num] = true;
  30. for (auto ch:adj[num]) {
  31. if (!vis[ch]) {
  32. dfs(ch,dis+1);
  33. }
  34. }
  35. }
  36. /////////////////////////////////////////////////////////////////////////////////////////////////////
  37.  
  38. void neverland() {
  39. int n; cin>>n;
  40. vis.clear();
  41. for (int i=1;i<n;i++)
  42. {
  43. int x,y;
  44. cin>>x>>y;
  45. adj[x].pb(y);
  46. adj[y].pb(x);
  47. }
  48. dfs(1,0);
  49. dfs(farLeaf,0);
  50. cout<<maxdis<<endl;
  51. }
  52. int main() {
  53. death;
  54. long long t=1;
  55. // cin>>t;
  56. while(t--){
  57. neverland();
  58. }
  59. }
Success #stdin #stdout 0.01s 5300KB
stdin
3
1 2
2 3

stdout
2