fork download
  1. # your code goes here
  2. import sys
  3. sys.setrecursionlimit(100000)
  4.  
  5. def dfs(node, parent, depth, adj):
  6. global max_depth, farthest_node
  7. if depth > max_depth:
  8. max_depth = depth
  9. farthest_node = node
  10. for neighbor in adj[node]:
  11. if neighbor != parent:
  12. dfs(neighbor, node, depth + 1, adj)
  13.  
  14. def longest_path_in_tree(n, edges):
  15. adj = [[] for _ in range(n + 1)]
  16. for u, v in edges:
  17. adj[u].append(v)
  18. adj[v].append(u)
  19.  
  20. # First DFS
  21. global max_depth, farthest_node
  22. max_depth = -1
  23. farthest_node = 1
  24. dfs(1, -1, 0, adj)
  25.  
  26. # Second DFS from the farthest node found
  27. max_depth = -1
  28. dfs(farthest_node, -1, 0, adj)
  29.  
  30. return max_depth
  31.  
  32. # Input parsing
  33. n = int(input())
  34. edges = [tuple(map(int, input().split())) for _ in range(n - 1)]
  35. print(longest_path_in_tree(n, edges))
  36.  
Success #stdin #stdout 0.13s 14144KB
stdin
3
1 2
2 3
stdout
2