from math import lcm n = int(input()) steps_to_reset = [1] * n resets_done = [1] * n has_input = [True] + [False] * (n - 1) inputs = [[] for i in range(n)] for i in range(n): neighbours = list(map(int, input().split())) k = neighbours[0] neighbours = neighbours[1:] if not has_input[i]: continue for val in neighbours: val -= 1 has_input[val] = True inputs[val].append(i) if not neighbours: continue if i == 0: steps_to_reset[0] = len(neighbours) continue my_lcm = lcm(*[steps_to_reset[prev] for prev in inputs[i]]) steps_done = sum(resets_done[prev] * my_lcm // steps_to_reset[prev] for prev in inputs[i]) steps_needed = lcm(steps_done, len(neighbours)) repeats = steps_needed // steps_done steps_to_reset[i] = my_lcm * repeats resets_done[i] = steps_needed // len(neighbours) print(lcm(*[steps_to_reset[node] for node in range(n) if has_input[node]]))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | from math import lcm n = int(input()) steps_to_reset = [1] * n resets_done = [1] * n has_input = [True] + [False] * (n - 1) inputs = [[] for i in range(n)] for i in range(n): neighbours = list(map(int, input().split())) k = neighbours[0] neighbours = neighbours[1:] if not has_input[i]: continue for val in neighbours: val -= 1 has_input[val] = True inputs[val].append(i) if not neighbours: continue if i == 0: steps_to_reset[0] = len(neighbours) continue my_lcm = lcm(*[steps_to_reset[prev] for prev in inputs[i]]) steps_done = sum(resets_done[prev] * my_lcm // steps_to_reset[prev] for prev in inputs[i]) steps_needed = lcm(steps_done, len(neighbours)) repeats = steps_needed // steps_done steps_to_reset[i] = my_lcm * repeats resets_done[i] = steps_needed // len(neighbours) print(lcm(*[steps_to_reset[node] for node in range(n) if has_input[node]])) |