fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. vector<vector<int> >graph;
  6. vector<bool> visited;
  7.  
  8. int max_distance, x;
  9. void DFS ( int node, int parent, int distance ){
  10.  
  11. if ( distance > max_distance ){
  12. max_distance = distance;
  13. x = node;
  14. }
  15.  
  16. for ( auto neighbour : graph[node] ){
  17. if ( neighbour != parent )
  18. DFS(neighbour, node, distance + 1);
  19. }
  20. }
  21.  
  22. int main()
  23. {
  24. int n, m;
  25. cin >> n >> m;
  26. graph.resize(n);
  27.  
  28. for ( int i = 0; i < m; i++ ){
  29. int u, v;
  30. cin >> u >> v;
  31. graph[u].emplace_back(v);
  32. graph[v].emplace_back(u);
  33. }
  34.  
  35. max_distance = -1;
  36. DFS(0, -1, 0);
  37. int y = x;
  38. max_distance = -1;
  39. DFS(y, -1, 0);
  40. int z = x;
  41.  
  42. int diameter = max_distance;
  43. cout << diameter << endl;
  44. return 0;
  45. }
  46.  
Success #stdin #stdout 0s 4328KB
stdin
10 9
0 1
0 2
1 3
1 4
2 5
2 6
3 7
3 8
3 9
stdout
5