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. idx = 0
  24. graphs = []
  25.  
  26. while idx < len(input):
  27. n = int(input[idx])
  28. idx += 1
  29. graph = defaultdict(list)
  30.  
  31. for i in range(n):
  32. line = list(map(int, input[idx].split()))
  33. graph[i] = line
  34. idx += 1
  35.  
  36. graphs.append(graph)
  37.  
  38. return graphs
  39.  
  40. def process_graph(graph):
  41. visited = set()
  42. heights = []
  43.  
  44. for node in graph:
  45. if node not in visited:
  46. height = bfs(graph, node, visited)
  47. heights.append(height)
  48.  
  49. return heights
  50.  
  51. def main():
  52. graphs = read_input()
  53.  
  54. results = []
  55. for graph in graphs:
  56. heights = process_graph(graph)
  57. results.append(heights)
  58.  
  59. for heights in results:
  60. print(" ".join(map(str, heights)))
  61.  
  62. main()
  63.  
Success #stdin #stdout 0.04s 9812KB
stdin
3
1
2
0 1
5
1 3
0 2 4
3
0 1 4
2 3
8
1 2 3
0
0 7
1 2
2 3
6
0 1 5
1 4
0
stdout
2
2
3 1