fork download
  1. import sys
  2. from collections import deque, defaultdict
  3.  
  4. def bfs(graph, start, visited):
  5. queue = deque([(start, 0)])
  6. visited.add(start)
  7. max_depth = 0
  8.  
  9. while queue:
  10. node, depth = queue.popleft()
  11. max_depth = max(max_depth, depth)
  12.  
  13. for neighbor in graph[node]:
  14. if neighbor not in visited:
  15. visited.add(neighbor)
  16. queue.append((neighbor, depth + 1))
  17.  
  18. return max_depth
  19.  
  20. # Read the input from stdin
  21. def read_input():
  22. input = sys.stdin.read().splitlines()
  23. n = int(input[0])
  24. graph = defaultdict(list)
  25.  
  26. for i in range(n):
  27. line = list(map(int, input[i + 1].split()))
  28. graph[i] = line
  29.  
  30. return graph
  31.  
  32. def main():
  33. graph = read_input()
  34.  
  35. visited = set()
  36. heights = []
  37.  
  38. for node in graph:
  39. if node not in visited:
  40. height = bfs(graph, node, visited)
  41. heights.append(height)
  42.  
  43. if len(heights)>0:
  44. for height in heights:
  45. if height>0:
  46. print(height, end=" ")
  47. else:
  48. print(0)
  49. print()
  50.  
  51. main()
  52.  
Success #stdin #stdout 0.04s 9816KB
stdin
8
1 2 3
0
0 7
1 2
2 3
6
0 1 5
1 4
stdout
3 1