from math import *
pl_in = []
pl_out = []
ch1 = []
ch2 = []
def roz(a1,a2, b):
return a1//gcd(a1, b), a2*b//gcd(a1,b)
def simplify(a1, a2):
return a1//gcd(a1,a2), a2//gcd(a1,a2)
def add(a1,b1, a2,b2):
return simplify(a1*b2+a2*b1, b1*b2)
result = 1
n = int(input())
for i in range(n):
pl_in.append([])
pl_out.append([])
ch1.append(0)
ch2.append(1)
for i in range(n):
r = [int(x) for x in input().split()]
for j in range(1, r[0]+1):
pl_in[r[j]-1].append(i)
pl_out[i].append(r[j]-1)
ch1[0], ch2[0] = 1,1
ch1[0], ch2[0] = roz(ch1[0], ch2[0], len(pl_out[0]))
for i in range(1,n):
if len(pl_out[i]) == 0:
continue
tmp1, tmp2 = 0,1
for j in pl_in[i]:
tmp1, tmp2 = add(tmp1, tmp2, ch1[j], ch2[j])
#print(tmp1, tmp2)
#print(tmp1, tmp2)
ch1[i], ch2[i] = roz(tmp1, tmp2, len(pl_out[i]))
ch1[i], ch2[i] = simplify(ch1[i],ch2[i])
#print(ch1[i], ch2[1])
result = lcm(result, ch2[i])
print(result)
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 | from math import * pl_in = [] pl_out = [] ch1 = [] ch2 = [] def roz(a1,a2, b): return a1//gcd(a1, b), a2*b//gcd(a1,b) def simplify(a1, a2): return a1//gcd(a1,a2), a2//gcd(a1,a2) def add(a1,b1, a2,b2): return simplify(a1*b2+a2*b1, b1*b2) result = 1 n = int(input()) for i in range(n): pl_in.append([]) pl_out.append([]) ch1.append(0) ch2.append(1) for i in range(n): r = [int(x) for x in input().split()] for j in range(1, r[0]+1): pl_in[r[j]-1].append(i) pl_out[i].append(r[j]-1) ch1[0], ch2[0] = 1,1 ch1[0], ch2[0] = roz(ch1[0], ch2[0], len(pl_out[0])) for i in range(1,n): if len(pl_out[i]) == 0: continue tmp1, tmp2 = 0,1 for j in pl_in[i]: tmp1, tmp2 = add(tmp1, tmp2, ch1[j], ch2[j]) #print(tmp1, tmp2) #print(tmp1, tmp2) ch1[i], ch2[i] = roz(tmp1, tmp2, len(pl_out[i])) ch1[i], ch2[i] = simplify(ch1[i],ch2[i]) #print(ch1[i], ch2[1]) result = lcm(result, ch2[i]) print(result) |
English