import math from math import gcd def lcm(a, b): return abs(a*b) // math.gcd(a, b) n = int(input()) adj = [] for i in range(n): adj.append(list(map(lambda x: x-1,map(int,input().split())))[1:]) res = 1 num = [0]*n den = [1]*n num[0] = 1 for i in range(n): if len(adj[i]) > 0: edge_num = num[i] edge_den = den[i]*len(adj[i]) dvsr = gcd(edge_num,edge_den) edge_num //= dvsr; edge_den //= dvsr; res = lcm(res, edge_den) for j in adj[i]: new_den = lcm(edge_den, den[j]) num[j] = num[j]*(new_den // den[j]) + edge_num*(new_den // edge_den) den[j] = new_den print(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 | import math from math import gcd def lcm(a, b): return abs(a*b) // math.gcd(a, b) n = int(input()) adj = [] for i in range(n): adj.append(list(map(lambda x: x-1,map(int,input().split())))[1:]) res = 1 num = [0]*n den = [1]*n num[0] = 1 for i in range(n): if len(adj[i]) > 0: edge_num = num[i] edge_den = den[i]*len(adj[i]) dvsr = gcd(edge_num,edge_den) edge_num //= dvsr; edge_den //= dvsr; res = lcm(res, edge_den) for j in adj[i]: new_den = lcm(edge_den, den[j]) num[j] = num[j]*(new_den // den[j]) + edge_num*(new_den // edge_den) den[j] = new_den print(res) |