Skip to content

Commit b60ffb4

Browse files
committed
Time: 446 ms (36.52%), Space: 100.7 MB (97.79%) - LeetHub
1 parent e76cc20 commit b60ffb4

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
class UnionFind:
2+
def __init__(self, n):
3+
self.parent = list(range(n + 1))
4+
self.rank = [0] * (n + 1)
5+
6+
def find(self, x):
7+
if self.parent[x] != x:
8+
self.parent[x] = self.find(self.parent[x])
9+
return self.parent[x]
10+
11+
def union(self, x, y):
12+
px, py = self.find(x), self.find(y)
13+
if px != py:
14+
if self.rank[px] < self.rank[py]:
15+
self.parent[px] = py
16+
elif self.rank[px] > self.rank[py]:
17+
self.parent[py] = px
18+
else:
19+
self.parent[py] = px
20+
self.rank[px] += 1
21+
22+
class Solution:
23+
def processQueries(self, c: int, connections: List[List[int]], queries: List[List[int]]) -> List[int]:
24+
# connected component를 만들어서, online 중 가장 작은 값을 찾아내라
25+
uf = UnionFind(c)
26+
for a, b in connections:
27+
uf.union(a, b)
28+
29+
groups = defaultdict(list)
30+
for i in range(1, c + 1):
31+
heapq.heappush(groups[uf.find(i)], i)
32+
33+
offline = set()
34+
ans = []
35+
36+
for k, v in queries:
37+
root = uf.find(v)
38+
39+
if k == 1:
40+
if v not in offline:
41+
ans.append(v)
42+
continue
43+
44+
heap = groups[root]
45+
while heap and heap[0] in offline:
46+
heapq.heappop(heap)
47+
48+
if not heap:
49+
ans.append(-1)
50+
else:
51+
ans.append(heap[0])
52+
53+
elif k == 2:
54+
offline.add(v)
55+
56+
return ans

0 commit comments

Comments
 (0)