E - 妨害された電力網 / Disrupted Power Grid Editorial by admin
Claude 4.6 Opus (Thinking)概要
最小全域木(MST)から1本の辺を除去されたとき、残りの辺で再び全域木を構成する際のコスト増加を考える問題です。敵は除去によるコスト増加を最大化(または連結不能に)するように辺を選びます。
考察
重要な観察1: MST辺の除去だけが意味を持つ
青木君がMSTに含まれない辺を妨害しても、高橋君は元のMSTをそのまま構築できるため、コストは変わりません。したがって、青木君はMSTに含まれる辺を妨害するのが最適です。
重要な観察2: 辺の置き換えと基本閉路
MST辺 \(e\)(重み \(w_e\))を除去すると、MSTは2つの連結成分に分かれます。再び連結にするには、この2成分を繋ぐ非MST辺(置き換え辺)を追加する必要があります。このとき新しいコストは:
\[\text{MST\_cost} - w_e + w_f\]
ここで \(w_f\) は置き換え辺の重みです。高橋君は \(w_f\) が最小の辺を選びます。
素朴なアプローチの問題
各MST辺について、それを覆う非MST辺の最小重みを求めたい。愚直にMST辺ごとに全非MST辺を調べると \(O(N \cdot M)\) でTLEします。
効率的な解法: Union-Find による縮約
非MST辺を重みの昇順に処理し、各辺 \((u, v, w)\) について、MST上の \(u\)-\(v\) パス上のまだマークされていない辺すべてに \(w\) を割り当てます。重みの昇順に処理するので、最初に割り当てられた値が最小値になります。マーク済みの辺を Union-Find で縮約することで、既にマークされた辺をスキップでき、全体の処理が高速になります。
アルゴリズム
- Kruskal法でMSTを構築:辺を重みでソートし、Union-Findで最小全域木を求める。
- MSTを根付き木として構成:BFSで各ノードの親・深さを計算する。
- LCA(最小共通祖先)の前処理:ダブリング(Binary Lifting)でLCAを \(O(\log N)\) で求められるようにする。
- 非MST辺を重み昇順にソートして処理:
- 各非MST辺 \((u, v, w)\) について、\(u\) と \(v\) からLCAまでMST上を上りながら、未マークのMST辺に \(w\) を記録。
- マーク済みの辺はUnion-Findで親と縮約し、次回以降スキップする。
- 答えの計算:
- 置き換え辺がないMST辺が存在 →
-1(連結不能) - そうでなければ、全MST辺について \(\text{MST\_cost} - w_e + \min\_replace_e\) の最大値を出力。
- 置き換え辺がないMST辺が存在 →
計算量
- 時間計算量: \(O(M \log M + N \log N)\)
- Kruskal法: \(O(M \log M)\)
- LCA前処理: \(O(N \log N)\)
- 非MST辺の処理: 各MST辺は1回だけマークされるため、合計 \(O(M \cdot \alpha(N))\)(\(\alpha\) はアッカーマン逆関数)
- 空間計算量: \(O(N \log N + M)\)(ダブリングテーブルと辺の格納)
実装のポイント
Union-Find の縮約テクニック: 非MST辺を昇順処理する際、マーク済みのMST辺の両端を縮約することで、次回パスを辿る際にスキップできます。これが高速化の鍵です。
根付き木における辺の対応: MST辺を「子ノード」に対応づけます(
par_edge_idx[v]で、ノード \(v\) からその親への辺を管理)。MST辺以外の妨害は無意味: コード中では全MST辺についてのみ置き換えコストを計算し、その最大値を答えとしています。
連結不能の判定: 置き換え辺が存在しないMST辺(グラフ全体の橋)があれば、青木君はそれを妨害して
-1にできます。ソースコード
import sys
from collections import defaultdict
def main():
input_data = sys.stdin.buffer.read().split()
idx = 0
N = int(input_data[idx]); idx += 1
M = int(input_data[idx]); idx += 1
edges = []
for i in range(M):
u = int(input_data[idx]); idx += 1
v = int(input_data[idx]); idx += 1
w = int(input_data[idx]); idx += 1
edges.append((w, u, v, i))
# Sort edges by weight
sorted_edges = sorted(edges)
# Union-Find
parent = list(range(N + 1))
rank = [0] * (N + 1)
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(x, y):
rx, ry = find(x), find(y)
if rx == ry:
return False
if rank[rx] < rank[ry]:
rx, ry = ry, rx
parent[ry] = rx
if rank[rx] == rank[ry]:
rank[rx] += 1
return True
# Build MST using Kruskal
mst_edges = [] # list of original edge indices in MST
mst_edge_set = set()
mst_cost = 0
for w, u, v, i in sorted_edges:
if union(u, v):
mst_edges.append((u, v, w, i))
mst_edge_set.add(i)
mst_cost += w
if len(mst_edges) == N - 1:
break
if len(mst_edges) < N - 1:
# Graph not connected even with all edges - shouldn't happen per constraints
print(-1)
return
# Build MST as a tree (adjacency list) with edge indices
# We need to handle: for each MST edge removed, what's the best replacement?
# Build adjacency list for MST tree
adj = defaultdict(list)
for idx_e, (u, v, w, eid) in enumerate(mst_edges):
adj[u].append((v, w, eid, idx_e))
adj[v].append((u, w, eid, idx_e))
# Root the tree at node 1, compute parent, depth, and euler tour for LCA
# For each non-MST edge, it creates a cycle. The best replacement for removing
# an MST edge e is the minimum weight non-MST edge whose fundamental cycle contains e.
# We use the technique: for each non-MST edge (u,v,w), it can replace any MST edge
# on the path from u to v in the MST. The replacement cost increase is w - (weight of removed edge).
# We want, for each MST edge, the minimum weight non-MST edge covering it.
# Use HLD or Euler tour + LCA with auxiliary structure
# Since N up to 2*10^5, we use binary lifting for LCA and path marking with "painting" technique
# For each MST edge, find the minimum weight non-tree edge that covers it.
# We use the "minimum on path" approach: for each non-tree edge (u,v,w),
# mark all MST edges on path u->v with min(current, w).
# This can be done efficiently with the "auxiliary minimum" approach using LCA + offline.
# We'll use the small-to-large or the approach of marking with BFS from leaves.
# Actually, a clean approach: use binary lifting LCA, then for each non-tree edge,
# walk up the path and update. But worst case O(M*N).
# Better: use the "minimum edge on path" with the technique from Tarjan's offline or
# use the approach of sorting non-tree edges by weight and using union-find to propagate.
# Efficient approach: Sort non-MST edges by weight. Process them in increasing order.
# For each non-MST edge (u,v,w), mark all unmarked MST edges on path u-v with w.
# Use a union-find where marked edges contract their endpoints.
# This way each MST edge is marked exactly once with the minimum weight non-tree edge covering it.
# Step 1: Build rooted tree, record parent edge for each node
from collections import deque
par = [0] * (N + 1)
par_edge_idx = [-1] * (N + 1) # index into mst_edges
depth = [0] * (N + 1)
visited = [False] * (N + 1)
root = 1
visited[root] = True
queue = deque([root])
order = []
while queue:
node = queue.popleft()
order.append(node)
for nxt, w, eid, eidx in adj[node]:
if not visited[nxt]:
visited[nxt] = True
par[nxt] = node
par_edge_idx[nxt] = eidx
depth[nxt] = depth[node] + 1
queue.append(nxt)
# Binary lifting for LCA
LOG = 18
up = [[0] * (N + 1) for _ in range(LOG)]
for v in range(1, N + 1):
up[0][v] = par[v]
up[0][root] = root
for k in range(1, LOG):
for v in range(1, N + 1):
up[k][v] = up[k-1][up[k-1][v]]
def lca(a, b):
if depth[a] < depth[b]:
a, b = b, a
diff = depth[a] - depth[b]
for k in range(LOG):
if (diff >> k) & 1:
a = up[k][a]
if a == b:
return a
for k in range(LOG - 1, -1, -1):
if up[k][a] != up[k][b]:
a = up[k][a]
b = up[k][b]
return up[0][a]
# Collect non-MST edges sorted by weight
non_mst_edges = []
for w, u, v, i in sorted_edges:
if i not in mst_edge_set:
non_mst_edges.append((w, u, v))
non_mst_edges.sort()
# For each MST edge (indexed by child node in rooted tree), find min weight non-tree edge covering it
# Use union-find contraction approach
uf_par = list(range(N + 1))
def uf_find(x):
while uf_par[x] != x:
uf_par[x] = uf_par[uf_par[x]]
x = uf_par[x]
return x
# min_replace[eidx] = minimum weight of non-tree edge covering MST edge eidx
# None means no non-tree edge covers it (bridge in terms of replacement)
min_replace = [None] * len(mst_edges)
for w, u, v in non_mst_edges:
l = lca(u, v)
# Walk from u up to l, marking unmarked edges
cu = uf_find(u)
while depth[cu] > depth[l]:
# The edge from cu to par[cu] is MST edge par_edge_idx[cu]
eidx = par_edge_idx[cu]
if min_replace[eidx] is None:
min_replace[eidx] = w
# Contract cu with its parent
p = uf_find(par[cu])
uf_par[cu] = p
cu = uf_find(p)
cv = uf_find(v)
while depth[cv] > depth[l]:
eidx = par_edge_idx[cv]
if min_replace[eidx] is None:
min_replace[eidx] = w
p = uf_find(par[cv])
uf_par[cv] = p
cv = uf_find(p)
# Now for each MST edge, if removed:
# - If min_replace[eidx] is None: removing it disconnects the graph -> cost = infinity
# - Otherwise: new MST cost = mst_cost - mst_edges[eidx].w + min_replace[eidx]
best = -1 # -1 means infinity is achievable
best_cost = -1
has_infinity = False
max_finite_cost = mst_cost # fallback
for eidx in range(len(mst_edges)):
u, v, w, eid = mst_edges[eidx]
if min_replace[eidx] is None:
has_infinity = True
break
else:
cost = mst_cost - w + min_replace[eidx]
if cost > best_cost:
best_cost = cost
if has_infinity:
print(-1)
else:
print(best_cost)
if __name__ == '__main__':
main()
この解説は claude4.6opus-thinking によって生成されました。