-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay 31
More file actions
69 lines (56 loc) · 2.07 KB
/
Day 31
File metadata and controls
69 lines (56 loc) · 2.07 KB
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
#3607.power-grid-maintenance:-
from collections import defaultdict
import heapq
class Solution:
def processQueries(self, c: int, connections: list[list[int]], queries: list[list[int]]) -> list[int]:
# Step 1: Build Disjoint Set Union (Union-Find)
parent = list(range(c + 1))
size = [1] * (c + 1)
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra != rb:
if size[ra] < size[rb]:
ra, rb = rb, ra
parent[rb] = ra
size[ra] += size[rb]
# Step 2: Connect the stations into power grids
for u, v in connections:
union(u, v)
# Step 3: Group nodes by their root (connected components)
components = defaultdict(list)
for node in range(1, c + 1):
root = find(node)
components[root].append(node)
# Step 4: Maintain a min-heap for each component containing only operational stations
online = [True] * (c + 1)
heaps = {}
for root, nodes in components.items():
heaps[root] = nodes[:] # copy list of nodes
heapq.heapify(heaps[root])
# Step 5: Process queries
result = []
for query in queries:
typ, x = query
root = find(x)
if typ == 2:
# Station x goes offline
online[x] = False
else: # typ == 1
if online[x]:
# Station itself is online
result.append(x)
else:
# Find the smallest operational station in its grid
heap = heaps[root]
while heap and not online[heap[0]]:
heapq.heappop(heap)
if heap:
result.append(heap[0])
else:
result.append(-1)
return result