結果
| 問題 | 
                            No.1390 Get together
                             | 
                    
| コンテスト | |
| ユーザー | 
                             lam6er
                         | 
                    
| 提出日時 | 2025-03-20 21:11:22 | 
| 言語 | PyPy3  (7.3.15)  | 
                    
| 結果 | 
                             
                                AC
                                 
                             
                            
                         | 
                    
| 実行時間 | 536 ms / 2,000 ms | 
| コード長 | 1,847 bytes | 
| コンパイル時間 | 155 ms | 
| コンパイル使用メモリ | 82,592 KB | 
| 実行使用メモリ | 184,024 KB | 
| 最終ジャッジ日時 | 2025-03-20 21:12:15 | 
| 合計ジャッジ時間 | 9,504 ms | 
| 
                            ジャッジサーバーID (参考情報)  | 
                        judge5 / judge4 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 3 | 
| other | AC * 29 | 
ソースコード
import sys
from collections import defaultdict
class UnionFind:
    def __init__(self, size):
        self.parent = list(range(size + 1))  # 1-based indexing
        self.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:
            return
        if self.rank[x_root] < self.rank[y_root]:
            self.parent[x_root] = y_root
        else:
            self.parent[y_root] = x_root
            if self.rank[x_root] == self.rank[y_root]:
                self.rank[x_root] += 1
def main():
    input = sys.stdin.read().split()
    ptr = 0
    N = int(input[ptr])
    ptr += 1
    M = int(input[ptr])
    ptr += 1
    
    color_b = defaultdict(set)  # color c -> set of boxes
    box_c = defaultdict(set)    # box b -> set of colors
    
    for _ in range(N):
        b = int(input[ptr])
        ptr += 1
        c = int(input[ptr])
        ptr += 1
        color_b[c].add(b)
        box_c[b].add(c)
    
    # Initialize Union-Find for colors up to N
    uf = UnionFind(N)
    
    # Connect all colors within the same box
    for b in box_c:
        colors = list(box_c[b])
        if len(colors) < 2:
            continue
        root = colors[0]
        for c in colors[1:]:
            uf.union(root, c)
    
    # Count the number of boxes per group
    counter = defaultdict(int)
    for b in box_c:
        colors = box_c[b]
        # Get any color in the box and find its root
        c = next(iter(colors))
        root = uf.find(c)
        counter[root] += 1
    
    # Calculate the answer
    ans = sum(k - 1 for k in counter.values())
    print(ans)
if __name__ == '__main__':
    main()
            
            
            
        
            
lam6er