結果
問題 | No.1390 Get together |
ユーザー |
![]() |
提出日時 | 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 typingclass 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 = nself.parent_or_size = [-1] * ndef merge(self, a: int, b: int) -> int:assert 0 <= a < self._nassert 0 <= b < self._nx = self.leader(a)y = self.leader(b)if x == y:return xif -self.parent_or_size[x] < -self.parent_or_size[y]:x, y = y, xself.parent_or_size[x] += self.parent_or_size[y]self.parent_or_size[y] = xreturn xdef same(self, a: int, b: int) -> bool:assert 0 <= a < self._nassert 0 <= b < self._nreturn self.leader(a) == self.leader(b)def leader(self, a: int) -> int:assert 0 <= a < self._nparent = self.parent_or_size[a]while parent >= 0:if self.parent_or_size[parent] < 0:return parentself.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 adef size(self, a: int) -> int:assert 0 <= a < self._nreturn -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 = 0slime_set = set()last = [-1] * slime_countuf = DSU(box_count)for _ in range(slime_count):box, color = map(int, input().split())box -= 1color -= 1if last[color] != -1 and not uf.same(last[color], box):uf.merge(last[color], box)result += 1last[color] = boxprint(result)