結果

問題 No.1420 国勢調査 (Easy)
ユーザー rlangevinrlangevin
提出日時 2023-05-07 12:46:34
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 343 ms / 2,000 ms
コード長 1,549 bytes
コンパイル時間 447 ms
コンパイル使用メモリ 86,664 KB
実行使用メモリ 83,384 KB
最終ジャッジ日時 2023-08-16 03:33:04
合計ジャッジ時間 9,611 ms
ジャッジサーバーID
(参考情報)
judge12 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 61 ms
71,212 KB
testcase_01 AC 63 ms
71,132 KB
testcase_02 AC 202 ms
78,892 KB
testcase_03 AC 206 ms
79,384 KB
testcase_04 AC 209 ms
79,028 KB
testcase_05 AC 206 ms
79,612 KB
testcase_06 AC 214 ms
78,660 KB
testcase_07 AC 195 ms
79,084 KB
testcase_08 AC 192 ms
79,144 KB
testcase_09 AC 190 ms
78,964 KB
testcase_10 AC 191 ms
79,192 KB
testcase_11 AC 195 ms
78,844 KB
testcase_12 AC 101 ms
80,756 KB
testcase_13 AC 122 ms
80,588 KB
testcase_14 AC 100 ms
80,556 KB
testcase_15 AC 120 ms
80,868 KB
testcase_16 AC 120 ms
80,712 KB
testcase_17 AC 121 ms
80,740 KB
testcase_18 AC 123 ms
81,188 KB
testcase_19 AC 117 ms
80,944 KB
testcase_20 AC 119 ms
80,828 KB
testcase_21 AC 119 ms
81,160 KB
testcase_22 AC 331 ms
83,376 KB
testcase_23 AC 343 ms
83,284 KB
testcase_24 AC 334 ms
82,888 KB
testcase_25 AC 338 ms
83,340 KB
testcase_26 AC 327 ms
83,384 KB
testcase_27 AC 288 ms
82,504 KB
testcase_28 AC 286 ms
82,112 KB
testcase_29 AC 292 ms
82,464 KB
testcase_30 AC 334 ms
82,240 KB
testcase_31 AC 293 ms
82,640 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.readline

class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]
        self.diff_weight = [0 for _ in range(n)]
        self.flag = 1

    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            root = self.find(self.par[x])
            self.diff_weight[x] ^= self.diff_weight[self.par[x]]
            self.par[x] = root
            return self.par[x]

    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        w ^= self.diff_weight[y]^self.diff_weight[x]
        if rx != ry:
            if self.rank[rx] < self.rank[ry]:
                rx, ry = ry, rx
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1
            self.par[ry] = rx
            self.size[rx] += self.size[ry]
            self.diff_weight[ry] = w
        else:
            if w:
                self.flag = 0


    def is_same(self, x, y):
        return self.find(x) == self.find(y)

    def get_size(self, x):
        x = self.find(x)
        return self.size[x]
    
    def diff(self, x, y):
        return self.diff_weight[y]^self.diff_weight[x]

N, M = map(int, input().split())
U = UnionFind(N)
for i in range(M):
    A, B = map(int, input().split())
    A, B = A - 1, B - 1
    Y = int(input())    
    U.union(A, B, Y)
    
if U.flag:
    for i in range(N):
        print(U.diff(U.find(i), i))
else:
    print(-1)
0