Official

E - 妨害された電力網 / Disrupted Power Grid Editorial by admin Editorial for printing

Claude 4.6 Opus (Thinking)

Overview

This problem considers the cost increase when reconstructing a spanning tree after one edge is removed from the Minimum Spanning Tree (MST). The adversary chooses the edge to remove in order to maximize the cost increase (or make the graph disconnected).

Analysis

Key Observation 1: Only removing MST edges matters

If Aoki sabotages an edge not in the MST, Takahashi can still construct the original MST as-is, so the cost doesn’t change. Therefore, it is optimal for Aoki to sabotage an edge contained in the MST.

Key Observation 2: Edge replacement and fundamental cycles

When an MST edge \(e\) (with weight \(w_e\)) is removed, the MST splits into two connected components. To reconnect them, a non-MST edge (replacement edge) connecting these two components must be added. The new cost becomes:

\[\text{MST\_cost} - w_e + w_f\]

where \(w_f\) is the weight of the replacement edge. Takahashi will choose the edge with minimum \(w_f\).

Problem with the naive approach

For each MST edge, we want to find the minimum weight among non-MST edges that cover it. Naively checking all non-MST edges for each MST edge results in \(O(N \cdot M)\), which causes TLE.

Efficient solution: Contraction using Union-Find

Process non-MST edges in ascending order of weight. For each edge \((u, v, w)\), assign \(w\) to all unmarked edges on the \(u\)-\(v\) path in the MST. Since we process in ascending order of weight, the first assigned value is the minimum. By contracting marked edges using Union-Find, we can skip already-marked edges, making the overall processing fast.

Algorithm

  1. Build MST using Kruskal’s algorithm: Sort edges by weight and find the minimum spanning tree using Union-Find.
  2. Construct MST as a rooted tree: Compute the parent and depth of each node using BFS.
  3. LCA (Lowest Common Ancestor) preprocessing: Use doubling (Binary Lifting) to answer LCA queries in \(O(\log N)\).
  4. Sort non-MST edges by weight in ascending order and process them:
    • For each non-MST edge \((u, v, w)\), traverse up the MST from \(u\) and \(v\) toward the LCA, recording \(w\) for each unmarked MST edge.
    • Marked edges are contracted with their parent using Union-Find, so they are skipped in subsequent iterations.
  5. Compute the answer:
    • If there exists an MST edge with no replacement edge → output -1 (cannot maintain connectivity)
    • Otherwise, output the maximum of \(\text{MST\_cost} - w_e + \min\_replace_e\) over all MST edges.

Complexity

  • Time complexity: \(O(M \log M + N \log N)\)
    • Kruskal’s algorithm: \(O(M \log M)\)
    • LCA preprocessing: \(O(N \log N)\)
    • Processing non-MST edges: Each MST edge is marked exactly once, so the total is \(O(M \cdot \alpha(N))\) (where \(\alpha\) is the inverse Ackermann function)
  • Space complexity: \(O(N \log N + M)\) (for the doubling table and edge storage)

Implementation Notes

  • Union-Find contraction technique: When processing non-MST edges in ascending order, contracting the endpoints of marked MST edges allows skipping them when traversing paths in subsequent iterations. This is the key to achieving fast performance.

  • Edge correspondence in the rooted tree: MST edges are associated with their “child node” (par_edge_idx[v] manages the edge from node \(v\) to its parent).

  • Sabotaging non-MST edges is meaningless: In the code, replacement costs are computed only for MST edges, and the maximum among them is the answer.

  • Determining disconnection: If there exists an MST edge with no replacement edge (a bridge of the entire graph), Aoki can sabotage it to achieve -1.

    Source Code

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()

This editorial was generated by claude4.6opus-thinking.

posted:
last update: