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
def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)

def lcm(a, b):
    return a * b // gcd(a, b)

def main():
    n = int(input())

    wch = [[] for i in range(0, n+2)]
    wych = [0 for i in range(0, n+2)]
    cyc_len = [1 for i in range(0, n+2)]
    bags_cnt = [0 for i in range (0, n + 2)]
    for source in range(1, n+1):
        line = list(map(int, input().strip().split()))
        wych[source] = line[0]
        for destination in line[1:]:
            wch[destination].append(source)

        if wych[source] == 0:
            wch[n+1].append(source)
            wych[source] = 1
    
    wych[n+1] = 1
    cyc_len[1] = wych[1]
    bags_cnt[1] = cyc_len[1]
    # print("i", 1, "cyc_len =", cyc_len[1], "bags_cnt = ", bags_cnt[1])
    # print(wch)
    for i in range(2, n+2):
        for j in wch[i]:
            cyc_len[i] = lcm(cyc_len[i], cyc_len[j])
        for j in wch[i]:
            bags_cnt[i] += bags_cnt[j] * (cyc_len[i] // cyc_len[j]) // wych[j]

        # Liczba walizek, musi być podzielna przez liczbę wychodzących krawędzi
        repeats = wych[i] // gcd(wych[i], bags_cnt[i])
        cyc_len[i] *= repeats
        bags_cnt[i] *= repeats
        # print("i", i, "cyc_len =", cyc_len[i], "bags_cnt = ", bags_cnt[i])

    
    print(cyc_len[n+1])

main()