結果

問題 No.1843 Tree ANDistance
ユーザー brthyyjp
提出日時 2022-02-19 15:28:00
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 396 ms / 2,000 ms
コード長 1,372 bytes
コンパイル時間 124 ms
コンパイル使用メモリ 82,308 KB
実行使用メモリ 142,456 KB
最終ジャッジ日時 2024-06-29 10:25:51
合計ジャッジ時間 9,160 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 38
権限があれば一括ダウンロードができます

ソースコード

diff #

class UnionFind:
    def __init__(self, n):
        self.par = [-1]*n
        self.rank = [0]*n

    def Find(self, x):
        if self.par[x] < 0:
            return x
        else:
            self.par[x] = self.Find(self.par[x])
            return self.par[x]

    def Unite(self, x, y):
        x = self.Find(x)
        y = self.Find(y)

        if x != y:
            if self.rank[x] < self.rank[y]:
                self.par[y] += self.par[x]
                self.par[x] = y
            else:
                self.par[x] += self.par[y]
                self.par[y] = x
                if self.rank[x] == self.rank[y]:
                    self.rank[x] += 1

    def Same(self, x, y):
        return self.Find(x) == self.Find(y)

    def Size(self, x):
        return -self.par[self.Find(x)]

mod = 10**9+7
P = [0]*33
P[0] = 1
for i in range(1, 33):
    P[i] = P[i-1]*2
    P[i] %= mod

import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

n = int(input())
E = []
for i in range(n-1):
    a, b, c = map(int, input().split())
    a, b = a-1, b-1
    E.append((a, b, c))

ans = 0
for i in range(32):
    uf = UnionFind(n)
    for a, b, c in E:
        if (c>>i)&1:
            uf.Unite(a, b)
    for j in range(n):
        if uf.par[j] < 0:
            c = uf.Size(j)
            ans += P[i]*(c*(c-1)//2)
            ans %= mod
print(ans)
0