結果
| 問題 |
No.1207 グラフX
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2025-03-12 00:05:25 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 835 ms / 2,000 ms |
| コード長 | 2,611 bytes |
| コンパイル時間 | 504 ms |
| コンパイル使用メモリ | 82,492 KB |
| 実行使用メモリ | 162,732 KB |
| 最終ジャッジ日時 | 2025-03-12 00:05:59 |
| 合計ジャッジ時間 | 32,671 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 46 |
ソースコード
## https://yukicoder.me/problems/no/1207
from collections import deque
MOD = 10 ** 9 + 7
class UnionFind:
"""
UnionFindの基本的な処理を実装したクラス
"""
def __init__(self, size):
self.root = [i for i in range(size)]
self.size = [1] * size
def get_root(self, v):
if v == self.root[v]:
return v
else:
old_root = self.root[v]
new_root = self.get_root(old_root)
self.root[v] = new_root
return new_root
def merge(self, u, v):
root_u = self.get_root(u)
root_v = self.get_root(v)
if root_u == root_v:
return False
if self.size[root_u] >= self.size[root_v]:
self.size[root_u] += self.size[root_v]
self.root[root_v] = root_u
self.root[v] = root_u
else:
self.size[root_v] += self.size[root_u]
self.root[root_u] = root_v
self.root[u] = root_v
return True
def main():
N, M, X = map(int, input().split())
xyz = []
for _ in range(M):
x, y, z = map(int, input().split())
xyz.append((x - 1, y - 1, z))
uf = UnionFind(N)
edges = []
for x, y, z in xyz:
if uf.merge(x, y):
edges.append((x, y, pow(X, z, MOD)))
next_nodes = [[] for _ in range(N)]
for x, y, _ in edges:
next_nodes[x].append(y)
next_nodes[y].append(x)
child_num = [0] * N
stack = deque()
parents = [-2] * N
parents[0] = -1
stack.append((0, 0))
while len(stack) > 0:
v, index = stack.pop()
while index < len(next_nodes[v]):
w = next_nodes[v][index]
if w == parents[v]:
index += 1
continue
parents[w] = v
stack.append((v, index + 1))
stack.append((w, 0))
break
if index == len(next_nodes[v]):
if parents[v] != -1:
child_num[parents[v]] += 1 + child_num[v]
answer = 0
for x, y, z in edges:
if parents[x] == y:
c_x = child_num[x] + 1
c_y = N - c_x
ans = (c_x * c_y) % MOD
ans *= z
ans %= MOD
answer += ans
answer %= MOD
elif parents[y] == x:
c_x = child_num[y] + 1
c_y = N - c_x
ans = (c_x * c_y) % MOD
ans *= z
ans %= MOD
answer += ans
answer %= MOD
print(answer)
if __name__ == "__main__":
main()