結果
| 問題 |
No.1207 グラフX
|
| コンテスト | |
| ユーザー |
lam6er
|
| 提出日時 | 2025-03-20 20:34:33 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 715 ms / 2,000 ms |
| コード長 | 2,671 bytes |
| コンパイル時間 | 380 ms |
| コンパイル使用メモリ | 82,248 KB |
| 実行使用メモリ | 229,116 KB |
| 最終ジャッジ日時 | 2025-03-20 20:36:32 |
| 合計ジャッジ時間 | 27,869 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 46 |
ソースコード
MOD = 10**9 + 7
def main():
import sys
input = sys.stdin.read
data = input().split()
idx = 0
N = int(data[idx]); idx +=1
M = int(data[idx]); idx +=1
X = int(data[idx]); idx +=1
edges = []
for _ in range(M):
x = int(data[idx])-1; idx +=1
y = int(data[idx])-1; idx +=1
z = int(data[idx]); idx +=1
edges.append((x, y, z))
# Kruskal's algorithm to build MST
parent = list(range(N))
def find(u):
while parent[u] != u:
parent[u] = parent[parent[u]]
u = parent[u]
return u
def union(u, v):
u_root = find(u)
v_root = find(v)
if u_root == v_root:
return False
parent[v_root] = u_root
return True
mst_edges = []
for x, y, z in edges:
if union(x, y):
mst_edges.append((x, y, z))
# Build adjacency list for MST
adj = [[] for _ in range(N)]
for x, y, z in mst_edges:
adj[x].append((y, z))
adj[y].append((x, z))
# Iterative DFS to compute subtree sizes and collect parent-child edges
from collections import deque
root = 0
visited = [False] * N
stack = [(root, -1)] # (node, parent)
subtree_size = [1] * N
parent_child_z = [] # (child, parent, z)
# Iterative DFS
stack = []
stack.append((root, -1))
while stack:
node, parent_node = stack.pop()
if node < 0:
# Post-processing, after children are processed
node = ~node
for neighbor, z in adj[node]:
if neighbor == parent_node:
continue
subtree_size[node] += subtree_size[neighbor]
continue
if visited[node]:
continue
visited[node] = True
# Push the node back with a marker to indicate post-processing
stack.append((~node, parent_node))
# Push children in reverse order to process them in order
# Iterate through all neighbors, but process only children
for neighbor, z in reversed(adj[node]):
if neighbor == parent_node:
continue
stack.append((neighbor, node))
# Record the parent-child edge and its z
parent_child_z.append((neighbor, node, z))
total = 0
for child, parent_node, z in parent_child_z:
s = subtree_size[child]
term = s * (N - s)
# Compute X^z mod MOD
pow_x_z = pow(X, z, MOD)
term = term * pow_x_z % MOD
total = (total + term) % MOD
print(total % MOD)
if __name__ == "__main__":
main()
lam6er