def gcd(a, b): if a == 0: return b if b == 0: return a r = a % b while r != 0: a = b b = r r = a % b return b def lcm(a, b): d = gcd(a, b) if d == 0: return 0 return (a // d) * b n = int(input()) nast = [] for i in range(n): # my_str = input() # list_of_strings = my_str.split(' ') # list_of_integers = list(map(int, list_of_strings[1:])) # nast.append(list_of_integers) lst = list(map(int, input().strip().split()))[1:] nast.append(lst) ile = [[0, 1] for _ in range(n)] ile[0] = [1, 1] # print(ile) # for i in range(n): # a = ile[i][0] # b = ile[i][1] # print(i, ': ', a, ' ', b, '\n') T = 1 for i in range(n): okres = len(nast[i]) li = ile[i][0] mi = ile[i][1] * okres # print(i + 1, ": ", li, okres, lcm(li, okres)) # if li != 0: # print(lcm(li, okres) // li, ile[i][1]) if li != 0: # coś wchodzi if okres != 0: # coś wychodzi if okres == 1: t = 1 else: t = (lcm(li, okres) // li) * ile[i][1] else: t = 1 # print('t =', t) T = lcm(T, t) for j in nast[i]: lj = ile[j - 1][0] mj = ile[j - 1][1] m = lcm(mi, mj) l = (m // mi) * li + (m // mj) * lj d = gcd(l, m) ile[j - 1][0] = l // d ile[j - 1][1] = m // d # print(ile) print(T)
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 62 63 64 65 66 67 68 69 70 71 | def gcd(a, b): if a == 0: return b if b == 0: return a r = a % b while r != 0: a = b b = r r = a % b return b def lcm(a, b): d = gcd(a, b) if d == 0: return 0 return (a // d) * b n = int(input()) nast = [] for i in range(n): # my_str = input() # list_of_strings = my_str.split(' ') # list_of_integers = list(map(int, list_of_strings[1:])) # nast.append(list_of_integers) lst = list(map(int, input().strip().split()))[1:] nast.append(lst) ile = [[0, 1] for _ in range(n)] ile[0] = [1, 1] # print(ile) # for i in range(n): # a = ile[i][0] # b = ile[i][1] # print(i, ': ', a, ' ', b, '\n') T = 1 for i in range(n): okres = len(nast[i]) li = ile[i][0] mi = ile[i][1] * okres # print(i + 1, ": ", li, okres, lcm(li, okres)) # if li != 0: # print(lcm(li, okres) // li, ile[i][1]) if li != 0: # coś wchodzi if okres != 0: # coś wychodzi if okres == 1: t = 1 else: t = (lcm(li, okres) // li) * ile[i][1] else: t = 1 # print('t =', t) T = lcm(T, t) for j in nast[i]: lj = ile[j - 1][0] mj = ile[j - 1][1] m = lcm(mi, mj) l = (m // mi) * li + (m // mj) * lj d = gcd(l, m) ile[j - 1][0] = l // d ile[j - 1][1] = m // d # print(ile) print(T) |