結果

問題 No.1207 グラフX
ユーザー H3PO4
提出日時 2021-12-25 16:03:10
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 850 ms / 2,000 ms
コード長 1,580 bytes
コンパイル時間 1,299 ms
コンパイル使用メモリ 81,920 KB
実行使用メモリ 159,544 KB
最終ジャッジ日時 2024-09-21 18:37:04
合計ジャッジ時間 30,822 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 46
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from collections import deque

input = sys.stdin.buffer.readline
MOD = 10 ** 9 + 7


class UnionFind:
    def __init__(self, n):
        self.n = n
        self.parent = [i for i in range(n)]
        self.height = [1] * n
        self.size = [1] * n

    def find(self, x):
        if self.parent[x] == x:
            return x
        else:
            self.parent[x] = self.find(self.parent[x])
            return self.parent[x]

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.height[x] < self.height[y]:
                self.parent[x] = y
                self.size[y] += self.size[x]
            else:
                self.parent[y] = x
                self.size[x] += self.size[y]
                if self.height[x] == self.height[y]:
                    self.height[x] += 1

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


N, M, X = map(int, input().split())
uf = UnionFind(N)
T = [[] for _ in range(N)]
for _ in range(M):
    x, y, z = map(int, input().split())
    x -= 1
    y -= 1
    if not uf.issame(x, y):
        uf.unite(x, y)
        T[x].append((y, z))
        T[y].append((x, z))

d = deque([(0, -1, 0)])
tour = []
while d:
    v, p, z = d.pop()
    tour.append((v, p, z))
    for x, xz in T[v]:
        if x != p:
            d.append((x, v, xz))

dp = [0] * N
ans = 0
for v, p, z in reversed(tour):
    dp[v] = 1
    for x, _ in T[v]:
        if x != p:
            dp[v] += dp[x]
    ans += pow(X, z, MOD) * dp[v] * (N - dp[v]) % MOD
ans %= MOD
print(ans)
0