E - 妨害された電力網 / Disrupted Power Grid Editorial by admin Editorial for printing
GPT 5.2 HighOverview
After Aoki disables one power line, Takahashi constructs a Minimum Spanning Tree (MST) with the remaining edges. Aoki wants to maximize the cost of this MST. We need to find the final cost (or -1 if it becomes impossible to connect).
Analysis
Key Insight
- The minimum cost Takahashi pays is “the weight of the MST on the remaining edges.”
- When one edge is removed, the MST weight can only change when an edge that belongs to the MST is removed.
- If a non-MST edge is removed, the same MST can still be used, so the cost remains unchanged (stays at \(W\)).
Therefore:
1. First, construct the MST of the original graph (with weight \(W\))
2. For each edge \(e\) in the MST, find the minimum-cost replacement edge when \(e\) is “removed”
- If no replacement edge exists, removing that edge disconnects the graph ⇒ Aoki can choose it, so the answer is -1
Why a Naive Approach Fails
If we remove each edge one by one and reconstruct the MST each time, we would run Kruskal up to \(M\) times: - This results in \(O(M \cdot M \log M)\) or similar, which is far too slow (\(M \le 2\times10^5\)).
How to Solve This (MST Sensitivity Analysis)
When a tree edge \(e\) is removed from the MST, the tree splits into two connected components. Let \(r_e\) be the minimum weight among edges that can reconnect these two components. Then: - The minimum cost after removal is \(W - w_e + r_e\) - If \(r_e\) doesn’t exist, the graph becomes disconnected
And \(r_e\) can be computed as follows: - Consider a non-tree edge \((u,v,w)\): the tree edges on the path from \(u\) to \(v\) in the MST can all be “replaced” by this non-tree edge ⇒ For each tree edge on the path, update \(r_e = \min(r_e, w)\)
In other words, we need “batch min-updates on an MST path for each non-tree edge.”
Algorithm
There are three main stages.
1. Construct MST using Kruskal’s Algorithm
- Sort edges by weight in ascending order and build the MST using DSU
- Let \(W\) be the total weight of the MST
- Build a tree (adjacency list) using only the edges adopted into the MST
2. Find the minimum replacement candidate \(r_e\) for each tree edge
What we want to do: - For each non-tree edge \((u,v,w)\), update \(r_e = \min(r_e, w)\) for all tree edges on the MST path from \(u\) to \(v\)
To do this efficiently, the code combines the following techniques:
(a) Heavy-Light Decomposition (HLD)
- Decomposes a path on the tree into \(O(\log N)\) intervals (contiguous ranges on an array)
- Assigns a position
pos[x]to each vertex, converting path updates into “range updates”
Here, tree edges are mapped to the “child vertex side”:
- The edge connecting to the parent corresponds to position pos[child] of that child vertex
- The root is excluded since it has no parent (position 0 is assigned to the root)
(b) Processing in ascending weight order + DSU-next for “filling only undetermined positions”
What we want is the minimum replacement weight for each tree edge. So: - Process non-tree edges in ascending order of weight - Only assign values to tree edges that haven’t been determined yet
To efficiently skip over “already determined positions” within a range, we use DSU-next (a Union-Find style structure pointing to the next unprocessed position):
- rep[pos] is INF if undetermined
- Once determined, no further updates are needed (since processing in ascending order guarantees the minimum is fixed)
- Each position is determined at most once, so the total work is nearly linear
As a result, we obtain the minimum replacement candidate \(r_e\) for each tree edge \(e\) (remains INF if none exists).
3. Compute the value Aoki maximizes
- If Aoki removes a non-tree edge: Takahashi can use the original MST, so the cost is \(W\)
- If Aoki removes a tree edge \(e\):
- If \(r_e\) exists: \(W - w_e + r_e\)
- If \(r_e\) doesn’t exist: disconnected ⇒ answer is
-1
Therefore:
- If any tree edge has \(r_e = \infty\), the answer is -1
- Otherwise, the answer is \(\max\left(W,\ \max_{e \in MST}(W - w_e + r_e)\right)\)
Complexity
- Time complexity:
- Kruskal: \(O(M \log M)\)
- HLD construction: \(O(N)\)
- Path decomposition per non-tree edge: \(O(M \log N)\)
- DSU-next filling processes each position once, so total \(O(N \alpha(N))\)
- Overall: \(O(M \log N)\) approximately
- Space complexity: \(O(N + M)\)
Implementation Notes
Map tree edges to “the position of the child vertex” (exclude the root) → To handle “edges” easily in path updates, we update like
update_segment(pos[a]+1, pos[b]), excluding the vertex on the LCA side.Processing non-tree edges in ascending weight order allows us to replace “min-update of minimum values” with “fix the value at first arrival.”
In Python, recursive DFS is dangerous, so the code uses stack-based DFS for safety.
If removing any MST edge makes the graph disconnected, Aoki can choose that edge, so the answer is immediately
-1.Source Code
import sys
INF = 10**30
class DSU:
__slots__ = ("p", "sz")
def __init__(self, n: int):
self.p = list(range(n))
self.sz = [1] * n
def find(self, x: int) -> int:
while self.p[x] != x:
self.p[x] = self.p[self.p[x]]
x = self.p[x]
return x
def union(self, a: int, b: int) -> bool:
a = self.find(a)
b = self.find(b)
if a == b:
return False
if self.sz[a] < self.sz[b]:
a, b = b, a
self.p[b] = a
self.sz[a] += self.sz[b]
return True
def main():
data = sys.stdin.buffer.read().split()
it = iter(data)
N = int(next(it))
M = int(next(it))
u = [0] * M
v = [0] * M
w = [0] * M
for i in range(M):
u[i] = int(next(it))
v[i] = int(next(it))
w[i] = int(next(it))
idx_sorted = list(range(M))
idx_sorted.sort(key=w.__getitem__)
dsu = DSU(N + 1)
in_mst = [False] * M
adj = [[] for _ in range(N + 1)]
mst_weight = 0
cnt = 0
for ei in idx_sorted:
a = u[ei]
b = v[ei]
if dsu.union(a, b):
in_mst[ei] = True
mst_weight += w[ei]
cnt += 1
adj[a].append((b, ei, w[ei]))
adj[b].append((a, ei, w[ei]))
if cnt == N - 1:
break
root = 1
parent = [0] * (N + 1)
depth = [0] * (N + 1)
parent_edge = [-1] * (N + 1)
stack = [root]
parent[root] = 0
depth[root] = 0
order = []
while stack:
x = stack.pop()
order.append(x)
for y, eid, _ww in adj[x]:
if y == parent[x]:
continue
parent[y] = x
depth[y] = depth[x] + 1
parent_edge[y] = eid
stack.append(y)
size = [1] * (N + 1)
heavy = [-1] * (N + 1)
for x in reversed(order):
maxsz = 0
for y, _, _ww in adj[x]:
if y == parent[x]:
continue
size[x] += size[y]
if size[y] > maxsz:
maxsz = size[y]
heavy[x] = y
head = [0] * (N + 1)
pos = [0] * (N + 1)
cur = 0
st = [(root, root)]
while st:
x, h = st.pop()
while x != -1 and x != 0:
head[x] = h
pos[x] = cur
cur += 1
hv = heavy[x]
for y, _, _ww in adj[x]:
if y == parent[x] or y == hv:
continue
st.append((y, y))
x = hv
mst_child = [-1] * M
for x in order:
eid = parent_edge[x]
if eid != -1:
mst_child[eid] = x
rep = [INF] * N # rep[pos[node]] for node != root
nxt = list(range(N + 1)) # DSU-next over positions, with sentinel N
def find_next(x: int) -> int:
while nxt[x] != x:
nxt[x] = nxt[nxt[x]]
x = nxt[x]
return x
def update_segment(l: int, r: int, val: int):
if l > r:
return
if l == 0:
l = 1
if l > r:
return
x = find_next(l)
while x <= r:
rep[x] = val
nxt[x] = x + 1
x = find_next(x)
def update_path(a: int, b: int, val: int):
while head[a] != head[b]:
if depth[head[a]] < depth[head[b]]:
a, b = b, a
ha = head[a]
update_segment(pos[ha], pos[a], val)
a = parent[ha]
if depth[a] > depth[b]:
a, b = b, a
update_segment(pos[a] + 1, pos[b], val)
for ei in idx_sorted:
if in_mst[ei]:
continue
update_path(u[ei], v[ei], w[ei])
ans = mst_weight
for ei in range(M):
if not in_mst[ei]:
continue
child = mst_child[ei]
r = rep[pos[child]]
if r >= INF:
print(-1)
return
cost = mst_weight - w[ei] + r
if cost > ans:
ans = cost
print(ans)
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.2-high.
posted:
last update: