結果

問題 No.1207 グラフX
ユーザー rlangevin
提出日時 2023-02-02 00:40:44
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,389 ms / 2,000 ms
コード長 1,871 bytes
コンパイル時間 239 ms
コンパイル使用メモリ 82,472 KB
実行使用メモリ 242,528 KB
最終ジャッジ日時 2024-07-01 17:23:41
合計ジャッジ時間 43,112 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 46
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
readline = 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)]

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

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    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 non_rec_dfs(s):
    stack = []
    stack.append(~s)
    stack.append(s)
    par = [-1] * N
    sz = [1] * N
    global ans
    while stack:
        u = stack.pop()
        if u >= 0:

            stack.append(~u)
            for v in G[u]:
                if v == par[u]:
                    continue
                par[v] = u
                stack.append(v)
        else:
            u = ~u
            sz[par[u]] += sz[u]
            if par[u] != -1:
                ans += dic[(u, par[u])] * sz[u] * (N - sz[u])
                ans %= mod


N, M, X = map(int, input().split())
mod = 10 ** 9 + 7
U = UnionFind(N)
D = []
for i in range(M):
    x, y, z = map(int, input().split())
    x, y = x - 1, y - 1
    D.append((z, x, y))
D.sort()

G = [[] for i in range(N)]
dic = dict()
for z, x, y in D:
    if U.is_same(x, y):
        continue
    U.union(x, y)
    G[x].append(y)
    G[y].append(x)
    v = pow(X, z, mod)
    dic[(x, y)] = v
    dic[(y, x)] = v
    
ans = 0
non_rec_dfs(0)
print(ans)
0