結果

問題 No.1207 グラフX
ユーザー brthyyjpbrthyyjp
提出日時 2020-09-06 22:38:33
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,569 ms / 2,000 ms
コード長 1,609 bytes
コンパイル時間 675 ms
コンパイル使用メモリ 82,432 KB
実行使用メモリ 241,268 KB
最終ジャッジ日時 2024-12-23 16:05:40
合計ジャッジ時間 48,286 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 46
権限があれば一括ダウンロードができます

ソースコード

diff #

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

def Unite(x, y, par, rank):
    x = Find(x, par)
    y = Find(y, par)

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

def Same(x, y, par):
    return Find(x, par) == Find(y, par)

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

def power(a, n, mod):
    bi=str(format(n,"b")) #2進数
    res=1
    for i in range(len(bi)):
        res=(res*res) %mod
        if bi[i]=="1":
            res=(res*a) %mod
    return res

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

n, m, X = map(int, input().split())

par = [-1]* n
rank = [0]*n

ans = 0
mod = 10**9+7
g = [[] for _ in range(n)]
d = {}
for i in range(m):
    x, y, z = map(int, input().split())
    x, y = x-1, y-1
    if Same(x, y, par):
        continue
    else:
        Unite(x, y, par, rank)
        w = power(X, z, mod)
        d[(x, y)] = w
        d[(y, x)] = w
        g[x].append(y)
        g[y].append(x)

s = []
visit = [-1]*n
s.append(0)
order = []
par = [-1]*n
while s:
    v = s.pop()
    order.append(v)
    for u in g[v]:
        if u == par[v]:
            continue
        par[u] = v
        s.append(u)

ans = 0
c = [1]*n
order.reverse()
for v in order:
    if par[v] != -1:
        ans += (n-c[v])*c[v]*d[(v, par[v])]
        c[par[v]] += c[v]
print(ans%mod)
0