import numpy as np import math def lcm(a, b): a = a // math.gcd(a, b) return a*b def div(a, b): (p, q) = a q = q * b g = math.gcd(p, q) return (p // g, q // g) def add(a, b): (p, q) = a (x, y) = b return (p*y + q*x, q*y) def full_lcm(vals): res = 1 for (p, q) in vals: if p == 0: continue res = lcm(res, q) return res def main(): n = int(input()) v = [[]] vals = [(0, 1) for _ in range(n+1)] vals[1] = (1, 1) for i in range(1, n+1): l = input().split(' ') v.append([int(x) for x in l[1:]]) for i in range(1, n+1): deg = len(v[i]) if vals[i][0] == 0 or deg == 0: vals[i] = (0, 1) continue vals[i] = div(vals[i], deg) for x in v[i]: vals[x] = add(vals[x], vals[i]) print(full_lcm(vals)) 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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | import numpy as np import math def lcm(a, b): a = a // math.gcd(a, b) return a*b def div(a, b): (p, q) = a q = q * b g = math.gcd(p, q) return (p // g, q // g) def add(a, b): (p, q) = a (x, y) = b return (p*y + q*x, q*y) def full_lcm(vals): res = 1 for (p, q) in vals: if p == 0: continue res = lcm(res, q) return res def main(): n = int(input()) v = [[]] vals = [(0, 1) for _ in range(n+1)] vals[1] = (1, 1) for i in range(1, n+1): l = input().split(' ') v.append([int(x) for x in l[1:]]) for i in range(1, n+1): deg = len(v[i]) if vals[i][0] == 0 or deg == 0: vals[i] = (0, 1) continue vals[i] = div(vals[i], deg) for x in v[i]: vals[x] = add(vals[x], vals[i]) print(full_lcm(vals)) if __name__=='__main__': main() |