結果

問題 No.416 旅行会社
ユーザー roarisroaris
提出日時 2020-12-09 19:44:41
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 845 ms / 4,000 ms
コード長 1,922 bytes
コンパイル時間 285 ms
コンパイル使用メモリ 87,140 KB
実行使用メモリ 154,308 KB
最終ジャッジ日時 2023-08-21 10:39:10
合計ジャッジ時間 10,157 ms
ジャッジサーバーID
(参考情報)
judge15 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 324 ms
119,964 KB
testcase_01 AC 74 ms
71,300 KB
testcase_02 AC 74 ms
71,432 KB
testcase_03 AC 72 ms
70,920 KB
testcase_04 AC 77 ms
71,256 KB
testcase_05 AC 73 ms
71,104 KB
testcase_06 AC 79 ms
71,304 KB
testcase_07 AC 87 ms
76,020 KB
testcase_08 AC 156 ms
78,784 KB
testcase_09 AC 246 ms
83,664 KB
testcase_10 AC 334 ms
120,128 KB
testcase_11 AC 309 ms
120,012 KB
testcase_12 AC 312 ms
119,876 KB
testcase_13 AC 308 ms
120,072 KB
testcase_14 AC 824 ms
154,248 KB
testcase_15 AC 804 ms
154,116 KB
testcase_16 AC 760 ms
154,308 KB
testcase_17 AC 845 ms
154,280 KB
testcase_18 AC 815 ms
154,044 KB
testcase_19 AC 647 ms
123,368 KB
testcase_20 AC 684 ms
123,400 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.readline

class Unionfind:
    def __init__(self, n):
        self.par = [-1]*n
        self.rank = [1]*n
        self.belong = [[v] for v in range(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
                
            for v in self.belong[rx]:
                self.belong[ry].append(v)
        else:
            self.par[rx] += self.par[ry]
            self.par[ry] = rx
            
            for v in self.belong[ry]:
                self.belong[rx].append(v)
            
    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, Q = map(int, input().split())
AB = [tuple(map(int, input().split())) for _ in range(M)]
CD = [tuple(map(int, input().split())) for _ in range(Q)]
s = set(10**7*C+D for C, D in CD)
uf = Unionfind(N)

for A, B in AB:
    if 10**7*A+B not in s:
        uf.unite(A-1, B-1)

ans = [0]*N

for v in uf.belong[uf.root(0)]:
    ans[v] = -1

for i in range(Q-1, -1, -1):
    C, D = CD[i]
    
    if uf.is_same(0, C-1) and not uf.is_same(0, D-1):
        for v in uf.belong[uf.root(D-1)]:
            ans[v] = i+1
    elif uf.is_same(0, D-1) and not uf.is_same(0, C-1):
        for v in uf.belong[uf.root(C-1)]:
            ans[v] = i+1
    
    uf.unite(C-1, D-1)

for ans_i in ans[1:]:
    print(ans_i)
0