結果

問題 No.1390 Get together
ユーザー roarisroaris
提出日時 2021-02-13 00:03:01
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 565 ms / 2,000 ms
コード長 1,481 bytes
コンパイル時間 929 ms
コンパイル使用メモリ 87,172 KB
実行使用メモリ 145,360 KB
最終ジャッジ日時 2023-09-27 07:50:26
合計ジャッジ時間 11,741 ms
ジャッジサーバーID
(参考情報)
judge14 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 81 ms
71,876 KB
testcase_01 AC 81 ms
71,700 KB
testcase_02 AC 84 ms
71,704 KB
testcase_03 AC 131 ms
79,788 KB
testcase_04 AC 115 ms
79,116 KB
testcase_05 AC 124 ms
79,488 KB
testcase_06 AC 121 ms
78,920 KB
testcase_07 AC 117 ms
78,704 KB
testcase_08 AC 124 ms
79,628 KB
testcase_09 AC 138 ms
79,652 KB
testcase_10 AC 84 ms
71,708 KB
testcase_11 AC 79 ms
71,812 KB
testcase_12 AC 82 ms
71,728 KB
testcase_13 AC 82 ms
71,412 KB
testcase_14 AC 82 ms
71,696 KB
testcase_15 AC 79 ms
71,704 KB
testcase_16 AC 283 ms
127,840 KB
testcase_17 AC 323 ms
111,120 KB
testcase_18 AC 273 ms
145,360 KB
testcase_19 AC 565 ms
133,196 KB
testcase_20 AC 500 ms
112,480 KB
testcase_21 AC 453 ms
112,512 KB
testcase_22 AC 474 ms
128,688 KB
testcase_23 AC 445 ms
135,244 KB
testcase_24 AC 435 ms
129,100 KB
testcase_25 AC 540 ms
133,760 KB
testcase_26 AC 519 ms
133,068 KB
testcase_27 AC 524 ms
133,588 KB
testcase_28 AC 515 ms
133,384 KB
testcase_29 AC 511 ms
133,440 KB
testcase_30 AC 515 ms
133,364 KB
testcase_31 AC 523 ms
133,396 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.readline
from collections import *

class Unionfind:
    def __init__(self, n):
        self.par = [-1]*n
        self.rank = [1]*n
    
    def root(self, x):
        r = x
        
        while not self.par[r]<0:
            r = self.par[r]
        
        t = x
        
        while t!=r:
            tmp = t
            t = self.par[t]
            self.par[tmp] = r
        
        return r
    
    def unite(self, x, y):
        rx = self.root(x)
        ry = self.root(y)
        
        if rx==ry:
            return
        
        if self.rank[rx]<=self.rank[ry]:
            self.par[ry] += self.par[rx]
            self.par[rx] = ry
            
            if self.rank[rx]==self.rank[ry]:
                self.rank[ry] += 1
        else:
            self.par[rx] += self.par[ry]
            self.par[ry] = rx
    
    def is_same(self, x, y):
        return self.root(x)==self.root(y)
    
    def count(self, x):
        return -self.par[self.root(x)]

N, M = map(int, input().split())
color = [[] for _ in range(M)]
box = [[] for _ in range(N)]

for _ in range(N):
    b, c = map(int, input().split())
    color[b-1].append(c-1)
    box[c-1].append(b-1)

uf = Unionfind(N)

for i in range(M):
    for j in range(len(color[i])-1):
        uf.unite(color[i][j], color[i][j+1])

s = defaultdict(set)

for i in range(N):
    for b in box[i]:
        s[uf.root(i)].add(b)

ans = 0

for v in s.values():
    ans += len(v)-1

print(ans)
0