from math import gcd, lcm def main(): n = int(input()) how_many = [0 for _ in range(n+1)] rounds = [0 for _ in range(n+1)] pair = [0, 0] result = 1 how_many[1] = 1 rounds[1] = 1 for i in range(1, n+1): x = input().split() r = int(x[0]) if r == 0 or how_many[i] == 0: continue if r >= 2: task = (rounds[i] * lcm(how_many[i], r)) // how_many[i] result = lcm(result, task) pair[0], pair[1] = how_many[i], rounds[i] * r to_add = [pair[0] // gcd(pair[0], pair[1]), pair[1] // gcd(pair[0], pair[1])] for j in range(1, len(x)): k = int(x[j]) if rounds[k] == 0: how_many[k], rounds[k] = to_add[0], to_add[1] else: LCM = lcm(to_add[1], rounds[k]) how_many[k] *= LCM // rounds[k] how_many[k] += ((to_add[0] * LCM) // to_add[1]) rounds[k] = LCM GCD = gcd(how_many[k], rounds[k]) how_many[k] //= GCD rounds[k] //= GCD print(result) if __name__ == '__main__': main()
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 math import gcd, lcm def main(): n = int(input()) how_many = [0 for _ in range(n+1)] rounds = [0 for _ in range(n+1)] pair = [0, 0] result = 1 how_many[1] = 1 rounds[1] = 1 for i in range(1, n+1): x = input().split() r = int(x[0]) if r == 0 or how_many[i] == 0: continue if r >= 2: task = (rounds[i] * lcm(how_many[i], r)) // how_many[i] result = lcm(result, task) pair[0], pair[1] = how_many[i], rounds[i] * r to_add = [pair[0] // gcd(pair[0], pair[1]), pair[1] // gcd(pair[0], pair[1])] for j in range(1, len(x)): k = int(x[j]) if rounds[k] == 0: how_many[k], rounds[k] = to_add[0], to_add[1] else: LCM = lcm(to_add[1], rounds[k]) how_many[k] *= LCM // rounds[k] how_many[k] += ((to_add[0] * LCM) // to_add[1]) rounds[k] = LCM GCD = gcd(how_many[k], rounds[k]) how_many[k] //= GCD rounds[k] //= GCD print(result) if __name__ == '__main__': main() |