from collections import defaultdict from collections import deque import math g = defaultdict(list) t = defaultdict(list) wch = [0]*(102) wych = [0]*(102) dp = [1]*(102) vis = [0]*(102) handled = [0]*(102) def gcd(a, b): while b > 0: a %= b t = b b = a a = t return a def lcm(a, b): return (a*b)//gcd(a, b) def dfs2(v, ile): if vis[v] == 1: return vis[v] = 1 dp[v] *= ile for u in g[v]: if vis[u] == 0 and handled[u] == 1: dfs2(u, ile) def dfs(v, ile): if vis[v] == 1: return vis[v] = 1 dp[v] *= ile for u in g[v]: if vis[u] == 0 and handled[u] == 1: dfs2(u, ile) for u in t[v]: if vis[u] == 0: dfs(u, ile) def main(): n = int(input()) for i in range(1, n+1): k = list(map(int, input().split())) for x in range(1, len(k)): g[i].append(k[x]) t[k[x]].append(i) wch[k[x]] += 1 wych[i] += 1 q = deque() for i in range(2, n+1): if wch[i] == 0: q.append(i) while len(q) > 0: v = q.popleft() for u in g[v]: wch[u] -= 1 t[u].remove(v) if wch[u] == 0: q.append(u) q.append(1) dp[1] = wych[1] while len(q) > 0: v = q.popleft() handled[v] = 1 if wych[v] == 0: continue if v != 1: sum = 0 for u in t[v]: sum += dp[u]//wych[u] if sum != 0: lc = lcm(sum, wych[v])//sum for x in range(1, 102): vis[x] = 0 dp[v] = sum dfs(v, lc) for u in g[v]: wch[u] -= 1 if wch[u] == 0: q.append(u) print(max(1, dp[1])) 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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | from collections import defaultdict from collections import deque import math g = defaultdict(list) t = defaultdict(list) wch = [0]*(102) wych = [0]*(102) dp = [1]*(102) vis = [0]*(102) handled = [0]*(102) def gcd(a, b): while b > 0: a %= b t = b b = a a = t return a def lcm(a, b): return (a*b)//gcd(a, b) def dfs2(v, ile): if vis[v] == 1: return vis[v] = 1 dp[v] *= ile for u in g[v]: if vis[u] == 0 and handled[u] == 1: dfs2(u, ile) def dfs(v, ile): if vis[v] == 1: return vis[v] = 1 dp[v] *= ile for u in g[v]: if vis[u] == 0 and handled[u] == 1: dfs2(u, ile) for u in t[v]: if vis[u] == 0: dfs(u, ile) def main(): n = int(input()) for i in range(1, n+1): k = list(map(int, input().split())) for x in range(1, len(k)): g[i].append(k[x]) t[k[x]].append(i) wch[k[x]] += 1 wych[i] += 1 q = deque() for i in range(2, n+1): if wch[i] == 0: q.append(i) while len(q) > 0: v = q.popleft() for u in g[v]: wch[u] -= 1 t[u].remove(v) if wch[u] == 0: q.append(u) q.append(1) dp[1] = wych[1] while len(q) > 0: v = q.popleft() handled[v] = 1 if wych[v] == 0: continue if v != 1: sum = 0 for u in t[v]: sum += dp[u]//wych[u] if sum != 0: lc = lcm(sum, wych[v])//sum for x in range(1, 102): vis[x] = 0 dp[v] = sum dfs(v, lc) for u in g[v]: wch[u] -= 1 if wch[u] == 0: q.append(u) print(max(1, dp[1])) if __name__ == '__main__': main() |