結果
| 問題 | 
                            No.1390 Get together
                             | 
                    
| コンテスト | |
| ユーザー | 
                             titia
                         | 
                    
| 提出日時 | 2021-02-12 21:43:11 | 
| 言語 | Python3  (3.13.1 + numpy 2.2.1 + scipy 1.14.1)  | 
                    
| 結果 | 
                             
                                AC
                                 
                             
                            
                         | 
                    
| 実行時間 | 867 ms / 2,000 ms | 
| コード長 | 878 bytes | 
| コンパイル時間 | 186 ms | 
| コンパイル使用メモリ | 12,672 KB | 
| 実行使用メモリ | 44,544 KB | 
| 最終ジャッジ日時 | 2024-07-19 20:50:08 | 
| 合計ジャッジ時間 | 15,756 ms | 
| 
                            ジャッジサーバーID (参考情報)  | 
                        judge4 / judge5 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 3 | 
| other | AC * 29 | 
ソースコード
import sys
input = sys.stdin.readline
N,M=map(int,input().split())
# UnionFind
Group = [i for i in range(M+1)] # グループ分け
Nodes = [1]*(M+1) # 各グループのノードの数
def find(x):
    while Group[x] != x:
        x=Group[x]
    return x
def Union(x,y):
    if find(x) != find(y):
        if Nodes[find(x)] < Nodes[find(y)]:
            
            Nodes[find(y)] += Nodes[find(x)]
            Nodes[find(x)] = 0
            Group[find(x)] = find(y)
            
        else:
            Nodes[find(x)] += Nodes[find(y)]
            Nodes[find(y)] = 0
            Group[find(y)] = find(x)
C=[[] for i in range(N+1)]
for i in range(N):
    b,c=map(int,input().split())
    C[c].append(b)
for i in range(N+1):
    for j in range(len(C[i])-1):
        Union(C[i][j],C[i][j+1])
ANS=0
for i in range(M+1):
    if i!=find(i):
        ANS+=1
print(ANS)
            
            
            
        
            
titia