-
Notifications
You must be signed in to change notification settings - Fork 15
/
contransmutation.py
87 lines (80 loc) · 2.54 KB
/
contransmutation.py
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
# Copyright (c) 2019 kamyu. All rights reserved.
#
# Google Code Jam 2019 Round 2 - Problem D. Contransmutation
# https://codingcompetitions.withgoogle.com/codejam/round/0000000000051679/0000000000146185
#
# Time: O(M)
# Space: O(M)
#
from collections import deque, defaultdict
def contransmutation():
M = input()
R = []
for _ in xrange(M):
R.append(map(lambda x: int(x)-1, raw_input().strip().split()))
G = map(int, raw_input().strip().split())
# pre-compute metals which can reach lead
parents = defaultdict(list)
for i in xrange(M):
for child in R[i]:
parents[child].append(i)
M_reach_lead = set([LEAD])
q = deque([LEAD])
while q:
i = q.popleft()
for j in parents[i]:
if j in M_reach_lead:
continue
M_reach_lead.add(j)
q.append(j)
# check if lead is reachable by initial G
R_reach_lead = defaultdict(list)
is_reachable = set()
q = deque()
for i in xrange(M):
if not G[i]:
continue
is_reachable.add(i)
R_reach_lead[i] = [child for child in R[i] if child in M_reach_lead]
q.append(i)
while q:
i = q.popleft()
for j in R_reach_lead[i]:
if j in is_reachable:
continue
is_reachable.add(j)
R_reach_lead[j] = [child for child in R[j] if child in M_reach_lead]
q.append(j)
if LEAD not in is_reachable: # early return if not reachable (optional)
return 0
# check if lead is bounded for making leads
if R_reach_lead[LEAD]:
curr = LEAD
if len(R_reach_lead[curr])-1 > 0:
return "UNBOUNDED"
curr = R_reach_lead[curr][0]
while curr != LEAD:
if len(R_reach_lead[curr])-1 > 0:
return "UNBOUNDED"
curr = R_reach_lead[curr][0]
R_reach_lead[curr] = [] # exclude lead to try topological sort
# Kahn's algorithm (topological sort)
indegree = defaultdict(int)
for i in xrange(M):
for j in R_reach_lead[i]:
indegree[j] += 1
dp = list(G)
q = deque([i for i in xrange(M) if i not in indegree])
while q:
i = q.popleft()
for j in R_reach_lead[i]:
dp[j] += dp[i]
indegree[j] -= 1
if indegree[j] == 0:
indegree.pop(j)
q.append(j)
return "UNBOUNDED" if indegree else dp[LEAD] % MOD
MOD = 10**9+7
LEAD = 0
for case in xrange(input()):
print 'Case #%d: %s' % (case+1, contransmutation())