結果
問題 | No.1390 Get together |
ユーザー | terry_u16 |
提出日時 | 2021-02-12 22:05:39 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 328 ms / 2,000 ms |
コード長 | 2,160 bytes |
コンパイル時間 | 145 ms |
コンパイル使用メモリ | 82,404 KB |
実行使用メモリ | 82,944 KB |
最終ジャッジ日時 | 2024-07-19 21:44:50 |
合計ジャッジ時間 | 7,709 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 29 |
ソースコード
import typing class DSU: ''' Implement (union by size) + (path halving) Reference: Zvi Galil and Giuseppe F. Italiano, Data structures and algorithms for disjoint set union problems ''' def __init__(self, n: int = 0) -> None: self._n = n self.parent_or_size = [-1] * n def merge(self, a: int, b: int) -> int: assert 0 <= a < self._n assert 0 <= b < self._n x = self.leader(a) y = self.leader(b) if x == y: return x if -self.parent_or_size[x] < -self.parent_or_size[y]: x, y = y, x self.parent_or_size[x] += self.parent_or_size[y] self.parent_or_size[y] = x return x def same(self, a: int, b: int) -> bool: assert 0 <= a < self._n assert 0 <= b < self._n return self.leader(a) == self.leader(b) def leader(self, a: int) -> int: assert 0 <= a < self._n parent = self.parent_or_size[a] while parent >= 0: if self.parent_or_size[parent] < 0: return parent self.parent_or_size[a], a, parent = ( self.parent_or_size[parent], self.parent_or_size[parent], self.parent_or_size[self.parent_or_size[parent]] ) return a def size(self, a: int) -> int: assert 0 <= a < self._n return -self.parent_or_size[self.leader(a)] def groups(self) -> typing.List[typing.List[int]]: leader_buf = [self.leader(i) for i in range(self._n)] result: typing.List[typing.List[int]] = [[] for _ in range(self._n)] for i in range(self._n): result[leader_buf[i]].append(i) return list(filter(lambda r: r, result)) slime_count, box_count = map(int, input().split()) result = 0 slime_set = set() last = [-1] * slime_count uf = DSU(box_count) for _ in range(slime_count): box, color = map(int, input().split()) box -= 1 color -= 1 if last[color] != -1 and not uf.same(last[color], box): uf.merge(last[color], box) result += 1 last[color] = box print(result)