|
| 1 | +# time complexity: O((c + q) * α(c)) |
| 2 | +# space complexity: O(c) |
| 3 | +from typing import List |
| 4 | +from collections import defaultdict |
| 5 | +from sortedcontainers import SortedSet |
| 6 | + |
| 7 | +class Solution: |
| 8 | + def processQueries(self, c: int, connections: List[List[int]], queries: List[List[int]]) -> List[int]: |
| 9 | + parent = list(range(c + 1)) |
| 10 | + |
| 11 | + def find(x): |
| 12 | + while x != parent[x]: |
| 13 | + parent[x] = parent[parent[x]] |
| 14 | + x = parent[x] |
| 15 | + return x |
| 16 | + |
| 17 | + def union(x, y): |
| 18 | + px, py = find(x), find(y) |
| 19 | + if px != py: |
| 20 | + parent[py] = px |
| 21 | + |
| 22 | + for u, v in connections: |
| 23 | + union(u, v) |
| 24 | + |
| 25 | + groupMembers = defaultdict(list) |
| 26 | + for node in range(1, c + 1): |
| 27 | + root = find(node) |
| 28 | + groupMembers[root].append(node) |
| 29 | + |
| 30 | + componentMap = dict() |
| 31 | + for root, members in groupMembers.items(): |
| 32 | + componentMap[root] = SortedSet(members) |
| 33 | + |
| 34 | + nodeToRoot = {node: find(node) for node in range(1, c + 1)} |
| 35 | + |
| 36 | + online = [True] * (c + 1) |
| 37 | + |
| 38 | + result = [] |
| 39 | + |
| 40 | + for type, x in queries: |
| 41 | + if type == 1: |
| 42 | + if online[x]: |
| 43 | + result.append(x) |
| 44 | + else: |
| 45 | + root = nodeToRoot[x] |
| 46 | + candidates = componentMap[root] |
| 47 | + if candidates: |
| 48 | + result.append(candidates[0]) |
| 49 | + else: |
| 50 | + result.append(-1) |
| 51 | + else: |
| 52 | + if online[x]: |
| 53 | + online[x] = False |
| 54 | + root = nodeToRoot[x] |
| 55 | + componentMap[root].discard(x) |
| 56 | + |
| 57 | + return result |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | +c = 5 |
| 62 | +connections = [[1, 2], [2, 3], [3, 4], [4, 5]] |
| 63 | +queries = [[1, 3], [2, 1], [1, 1], [2, 2], [1, 2]] |
| 64 | +print(Solution().processQueries(c, connections, queries)) |
| 65 | +c = 3 |
| 66 | +connections = [] |
| 67 | +queries = [[1, 1], [2, 1], [1, 1]] |
| 68 | +print(Solution().processQueries(c, connections, queries)) |
0 commit comments