結果

問題 No.1843 Tree ANDistance
ユーザー customaddone
提出日時 2022-03-05 00:47:33
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 384 ms / 2,000 ms
コード長 2,469 bytes
コンパイル時間 156 ms
コンパイル使用メモリ 82,540 KB
実行使用メモリ 114,652 KB
最終ジャッジ日時 2024-07-18 23:52:05
合計ジャッジ時間 10,850 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 38
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
import math
from copy import deepcopy
from itertools import combinations, permutations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right

import sys

def input():
    return sys.stdin.readline().rstrip()
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getListGraph():
    return list(map(lambda x:int(x) - 1, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]

mod = 10 ** 9 + 7
MOD = 998244353
# import pypyjit
# pypyjit.set_param('max_unroll_recursion=-1')
sys.setrecursionlimit(10000000)
inf = float('inf')
eps = 10 ** (-15)
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]

#############
# Main Code #
#############

"""
UFってこと
"""

# ルートの決定方法はいじれる
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

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

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        # 謎のREが起こったらrootの設定方法を変えよう
        if self.parents[x] > self.parents[y]:
            x, y = y, x
        # if x > y: # よりrootのインデックスが小さい方が親
            # x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

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

    def size(self, x):
        return -self.parents[self.find(x)]

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

N = getN()
E = []
for _ in range(N - 1):
    a, b, c = getNM()
    E.append([a - 1, b - 1, c])

ans = 0
for i in range(32):
    U = UnionFind(N)
    for a, b, c in E:
        if c & (1 << i):
            U.union(a, b)
    for j in range(N):
        if j == U.find(j):
            t = U.size(j)
            ans += (1 << i) * (t * (t - 1) // 2)
            ans %= mod

print(ans)
0