-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathroad_to_nutella2.py3
196 lines (185 loc) · 6.36 KB
/
road_to_nutella2.py3
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# Copyright (c) 2023 kamyu. All rights reserved.
#
# Meta Hacker Cup 2023 Practice Round - Problem D. Road to Nutella
# https://www.facebook.com/codingcompetitions/hacker-cup/2023/practice-round/problems/D
#
# Time: O(N + M + QlogQ)
# Space: O(N + M + Q)
#
# template: https://github.com/kamyu104/GoogleCodeJam-Farewell-Rounds/blob/main/Round%20B/railroad_maintenance.py3
# reference: https://en.wikipedia.org/wiki/Biconnected_component
def iter_biconnected_components(graph): # Time: O(|V| + |E|) = O(N + 2N) = O(N), Space: O(|V|) = O(N)
def iter_biconnect(v, p):
stk = [(1, (v, p))]
while stk:
step, args = stk.pop()
if step == 1:
v, p = args
index[v] = index_counter[0]
lowlinks[v] = index_counter[0]
index_counter[0] += 1
stack_set.add(v)
stack.append(v)
stk.append((4, (v, p)))
for w in reversed(graph[v]):
if w == p:
continue
stk.append((2, (w, v)))
elif step == 2:
w, v = args
if w not in index:
stk.append((3, (w, v)))
stk.append((1, (w, v)))
elif w in stack_set:
lowlinks[v] = min(lowlinks[v], index[w])
elif step == 3:
w, v = args
lowlinks[v] = min(lowlinks[v], lowlinks[w])
elif step == 4:
v, p = args
if lowlinks[v] == index[v]:
biconnected_component = []
w = None
while w != v:
w = stack.pop()
stack_set.remove(w)
biconnected_component.append(w)
bccs.append(set(biconnected_component))
index_counter, index, lowlinks = [0], {}, {}
stack, stack_set = [], set()
bccs = []
for v in range(len(graph)):
if v not in index:
iter_biconnect(v, -1)
return bccs
def inplace_counting_sort(idxs, cb, reverse=False): # Time: O(n)
if not idxs:
return
count = [0]*(max(cb(idx) for idx in idxs)+1)
for idx in idxs:
count[cb(idx)] += 1
for i in range(1, len(count)):
count[i] += count[i-1]
for i in reversed(range(len(idxs))): # inplace but unstable sort
while idxs[i] >= 0:
count[cb(idxs[i])] -= 1
j = count[cb(idxs[i])]
idxs[i], idxs[j] = idxs[j], ~idxs[i]
for i in range(len(idxs)):
idxs[i] = ~idxs[i] # restore values
if reverse: # unstable sort
idxs.reverse()
class UnionFind(object): # Time: O(n * alpha(n)), Space: O(n)
def __init__(self, n):
self.set = list(range(n))
self.rank = [0]*n
self.group = [set() for _ in range(n)] # added
def find_set(self, x):
stk = []
while self.set[x] != x: # path compression
stk.append(x)
x = self.set[x]
while stk:
self.set[stk.pop()] = x
return x
def union_set(self, x, y):
x, y = self.find_set(x), self.find_set(y)
if x == y:
return 0 # modified
if self.rank[x] > self.rank[y]: # union by rank
x, y = y, x
self.set[x] = self.set[y]
if self.rank[x] == self.rank[y]:
self.rank[y] += 1
# added below
if len(self.group[x]) > len(self.group[y]): # move from smaller group to bigger one, total time: O(QlogQ)
self.group[x], self.group[y] = self.group[y], self.group[x]
result = 0
for i in self.group[x]:
if i not in self.group[y]:
self.group[y].add(i)
else:
self.group[y].remove(i)
result += 1
self.group[x].clear()
return result # modified
def group_add(self, u, i):
self.group[u].add(i)
def is_bipartite(bcc, adj, color): # a graph is bipartite if and only if it contains no odd cycles
root = next(iter(bcc))
color[root] = 0
q = [root]
while q:
new_q = []
for u in q:
for v in adj[u]:
if v not in bcc:
continue
if color[v] != -1:
if color[v] != color[u]^1:
return False # cannot be bipartite colored
continue
color[v] = color[u]^1
new_q.append(v)
q = new_q
return True
def find_dist(bccs, adj, adj2):
color = [-1]*len(adj)
q = [i for i, bcc in enumerate(bccs) if not is_bipartite(bcc, adj, color)]
if not q:
return []
dist = [-1 for _ in range(len(bccs))]
for u in q:
dist[u] = 0
while q:
new_q = []
for u in q:
for v in adj2[u]:
if dist[v] != -1:
continue
dist[v] = dist[u]+1
new_q.append(v)
q = new_q
return dist
def road_to_nutella():
N, M = list(map(int, input().split()))
edges = [list(map(lambda x: int(x)-1, input().split())) for _ in range(M)]
Q = int(input())
queries = [list(map(lambda x: int(x)-1, input().split())) for _ in range(Q)]
adj = [[] for _ in range(N)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
bccs = iter_biconnected_components(adj)
lookup = [-1]*N
for i, bcc in enumerate(bccs):
for u in bcc:
lookup[u] = i
adj2 = [[] for _ in range(len(bccs))]
for u, v in edges:
nu, nv = lookup[u], lookup[v]
if nu == nv:
continue
adj2[nu].append(nv)
adj2[nv].append(nu)
dist = find_dist(bccs, adj, adj2)
if not dist:
return -1*len(queries)
uf = UnionFind(len(adj2))
result = 0
for i, (a, b) in enumerate(queries):
u, v = lookup[a], lookup[b]
if u == v:
result += dist[u]
else:
uf.group_add(u, i)
uf.group_add(v, i)
idxs = list(range(len(adj2)))
inplace_counting_sort(idxs, lambda x: dist[x], reverse=True) # Time: O(N)
lookup2 = [False]*len(adj2)
for u in idxs:
lookup2[u] = True
result += dist[u]*sum(uf.union_set(u, v) for v in adj2[u] if lookup2[v])
return result
for case in range(int(input())):
print('Case #%d: %s' % (case+1, road_to_nutella()))