from sys import stdin, stdout def computeGCD(x, y): x, y = max(x, y), min(x, y) while(y > 0): x, y = y, x % y return x n = int(stdin.readline()) target_len = [0] * n target_list = [] for i in range(n): target_len[i], *l = [int(x) - 1 for x in stdin.readline().split()] target_len[i] += 1 target_list.append(l) active = [False] * n active[0] = True for i, targets in enumerate(target_list): if active[i]: for t in targets: active[t] = True sources = [list() for _ in range(n)] for i, targets in enumerate(target_list): if active[i]: for t in targets: sources[t].append(i) recieving_fraction = [(0, 0)] * n recieving_fraction[0] = (1, 1) # licznik, mianownik res = max(target_len[0], 1) for i in range(1, n): if active[i] & (target_len[i] > 0): recieved = sum([(res*recieving_fraction[k][0])//(target_len[k]*recieving_fraction[k][1]) for k in sources[i]]) reduce_factor = computeGCD(recieved, res) recieving_fraction[i] = (recieved//reduce_factor, res//reduce_factor) res *= target_len[i] // computeGCD(target_len[i], recieved) stdout.write(str(res))
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 41 | from sys import stdin, stdout def computeGCD(x, y): x, y = max(x, y), min(x, y) while(y > 0): x, y = y, x % y return x n = int(stdin.readline()) target_len = [0] * n target_list = [] for i in range(n): target_len[i], *l = [int(x) - 1 for x in stdin.readline().split()] target_len[i] += 1 target_list.append(l) active = [False] * n active[0] = True for i, targets in enumerate(target_list): if active[i]: for t in targets: active[t] = True sources = [list() for _ in range(n)] for i, targets in enumerate(target_list): if active[i]: for t in targets: sources[t].append(i) recieving_fraction = [(0, 0)] * n recieving_fraction[0] = (1, 1) # licznik, mianownik res = max(target_len[0], 1) for i in range(1, n): if active[i] & (target_len[i] > 0): recieved = sum([(res*recieving_fraction[k][0])//(target_len[k]*recieving_fraction[k][1]) for k in sources[i]]) reduce_factor = computeGCD(recieved, res) recieving_fraction[i] = (recieved//reduce_factor, res//reduce_factor) res *= target_len[i] // computeGCD(target_len[i], recieved) stdout.write(str(res)) |