結果
問題 | No.1390 Get together |
ユーザー |
![]() |
提出日時 | 2025-03-20 18:51:35 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 572 ms / 2,000 ms |
コード長 | 1,847 bytes |
コンパイル時間 | 174 ms |
コンパイル使用メモリ | 82,760 KB |
実行使用メモリ | 184,028 KB |
最終ジャッジ日時 | 2025-03-20 18:53:00 |
合計ジャッジ時間 | 10,875 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 29 |
ソースコード
import sysfrom collections import defaultdictclass UnionFind:def __init__(self, size):self.parent = list(range(size + 1)) # 1-based indexingself.rank = [0] * (size + 1)def find(self, x):if self.parent[x] != x:self.parent[x] = self.find(self.parent[x])return self.parent[x]def union(self, x, y):x_root = self.find(x)y_root = self.find(y)if x_root == y_root:returnif self.rank[x_root] < self.rank[y_root]:self.parent[x_root] = y_rootelse:self.parent[y_root] = x_rootif self.rank[x_root] == self.rank[y_root]:self.rank[x_root] += 1def main():input = sys.stdin.read().split()ptr = 0N = int(input[ptr])ptr += 1M = int(input[ptr])ptr += 1color_b = defaultdict(set) # color c -> set of boxesbox_c = defaultdict(set) # box b -> set of colorsfor _ in range(N):b = int(input[ptr])ptr += 1c = int(input[ptr])ptr += 1color_b[c].add(b)box_c[b].add(c)# Initialize Union-Find for colors up to Nuf = UnionFind(N)# Connect all colors within the same boxfor b in box_c:colors = list(box_c[b])if len(colors) < 2:continueroot = colors[0]for c in colors[1:]:uf.union(root, c)# Count the number of boxes per groupcounter = defaultdict(int)for b in box_c:colors = box_c[b]# Get any color in the box and find its rootc = next(iter(colors))root = uf.find(c)counter[root] += 1# Calculate the answerans = sum(k - 1 for k in counter.values())print(ans)if __name__ == '__main__':main()