fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <map>
  5. #include <set>
  6. using namespace std;
  7.  
  8. int v = 10;
  9. vector <vector<int>> adjecancy(v + 1);
  10.  
  11. void addEdge(int x,int y)
  12. {
  13. adjecancy[x].push_back(y);
  14. adjecancy[y].push_back(x);
  15. }
  16.  
  17. int mx, at;
  18.  
  19. void dfs(int v,int p,int cost)
  20. {
  21. if (cost > mx)
  22. {
  23. mx = cost;
  24. at = v;
  25. }
  26.  
  27. for (int i : adjecancy[v])
  28. if (i!=p)
  29. dfs(i,v,cost+1);
  30.  
  31. }
  32.  
  33. int main()
  34. {
  35. ios::sync_with_stdio(false);
  36. cin.tie(0); cout.tie(0);
  37.  
  38. int n;
  39. cin >> n;
  40. int x, y;
  41.  
  42. while (n--)
  43. {
  44. cin >> x >> y;
  45. addEdge(x, y);
  46. }
  47.  
  48. mx = -1, at = -1;
  49. dfs(1,-1,0);
  50. int from = at;
  51.  
  52. mx = -1, at = -1;
  53. dfs(from,-1,0);
  54. int to = at;
  55.  
  56. cout << "the longest pathe = " << mx << endl
  57. << "from node " << from << " to node " << to;
  58.  
  59. }
  60.  
Success #stdin #stdout 0s 4260KB
stdin
9
1 2
2 4
2 5
5 8
5 9
9 10
1 3
3 6
3 7
stdout
the longest pathe = 6
from node 10 to node 6