Official

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

gemini-3.5-flash-thinking

Overview

This problem asks us to find the maximum cost of the minimum spanning tree that can be constructed from the remaining edges after removing one edge from the Minimum Spanning Tree (MST) of a given graph.

Aoki tries to maximize Takahashi’s construction cost, while Takahashi tries to build a spanning tree with minimum cost from the remaining edges. We simulate the optimal actions of both players and efficiently compute the final cost.


Analysis

1. Which edge should Aoki destroy?

First, let \(T\) denote the MST of the entire graph, and \(W_{mst}\) its total cost.

  • If Aoki destroys an edge not in \(T\) (a non-MST edge): Takahashi can still use all edges of \(T\), so the minimum cost remains \(W_{mst}\) unchanged.
  • If Aoki destroys an edge \(e\) in \(T\) (an MST edge): Takahashi needs to use a different edge \(e'\) instead of \(e\) to keep the graph connected. In this case, the minimum cost Takahashi pays is \(W_{mst} - w(e) + w(e')\), which is always at least \(W_{mst}\).

Therefore, Aoki will always destroy one of the edges in the MST (an MST edge).

2. Conditions for Takahashi’s “replacement edge”

When an edge \(e\) is removed from the MST, the tree \(T\) splits into two connected components (groups). To reconnect them, we must add one non-MST edge \(e'\) that bridges these two groups.

Such an edge \(e'\) is called a replacement edge. From properties of trees, a non-MST edge \(e' = (u, v)\) can serve as a replacement for \(e\) if and only if “the edge \(e\) lies on the simple path between vertices \(u\) and \(v\) in the original tree \(T\)”.

Since Takahashi wants to minimize cost, when edge \(e\) is removed, he chooses the replacement edge \(e'\) satisfying the condition with the smallest cost \(w(e')\).

3. Naive approach and improvement

For all MST edges \(e\) (\(N-1\) edges in total), if we remove each one and reapply Kruskal’s algorithm to find the MST of the remaining graph, each iteration takes \(O(M \log M)\) time. The total time becomes \(O(NM \log M)\), which exceeds the time limit (TLE) under the constraints (\(N, M \le 2 \times 10^5\)).

Instead, we reverse our perspective. We consider the approach: “For each non-MST edge \(e' = (u, v)\), distribute it to all MST edges \(e\) on the path in \(T\) that it can replace.”

We process non-MST edges in ascending order of cost, and for MST edges on the path between \(u\) and \(v\) in \(T\) that “have not yet been assigned a replacement edge”, we assign the cost \(w(e')\). Edges that already have a replacement edge assigned (with smaller cost) are skipped.

This operation of “efficiently finding unupdated edges on the path and skipping already-updated edges” can be done efficiently using a Union-Find (Disjoint Set Union) data structure.


Algorithm

We compute the answer with the following steps.

Step 1: Build the Minimum Spanning Tree (MST)

Use Kruskal’s algorithm to find the MST of the entire graph. * If the number of MST edges is less than \(N-1\), the graph is not connected in the first place, so output -1 and terminate. * Classify edges into “edges in the MST (MST edges)” and “edges not in the MST (non-MST edges)”.

Step 2: Convert MST to a rooted tree

Build a rooted tree with vertex \(0\) as the root of the MST. Using BFS (Breadth-First Search) or similar, record for each vertex \(i\) the “index of the edge to its parent”, “cost of the edge to its parent”, and “depth (distance from the root)”.

Step 3: Determine replacement edges using Union-Find

Prepare a Union-Find to manage replacement edges. Initially, each vertex belongs to its own group. The representative of each group in this Union-Find points to “the vertex closest to the root (with minimum depth) within that group”.

Process non-MST edges \(e' = (u, v)\) in ascending order of cost. 1. Let \(curr\_u, curr\_v\) be the current group representatives (= vertices closest to the root) of \(u\) and \(v\), respectively. 2. While \(curr\_u\) and \(curr\_v\) are different, repeat the following operations (imagine climbing toward the LCA (Lowest Common Ancestor)): * Choose the vertex with greater depth (say \(curr\_u\)). * Set the replacement edge cost of the MST edge connecting \(curr\_u\) to its parent to \(w(e')\). * Merge (union) \(curr\_u\) into its parent’s group. This marks this edge as “updated”, and it will be skipped in future iterations. * Update \(curr\_u\) to the new representative (the representative of the parent), and continue the loop.

With this technique, each MST edge gets a replacement edge written exactly once, and already-updated paths are skipped efficiently via Union-Find path compression.

Step 4: Compute the maximum cost

For all MST edges \(e\), check the minimum replacement cost \(alt\_cost[e]\). * If there exists an MST edge whose \(alt\_cost[e]\) remains at the initial value (\(\infty\)), removing that edge makes the graph disconnected, so Aoki will destroy that edge. In this case, output -1. * Otherwise, compute the maximum of \(W_{mst} - w(e) + alt\_cost[e]\) over all MST edges, and output it.


Complexity

  • Time complexity: \(O(M \log M)\)
    • Sorting edges takes \(O(M \log M)\).
    • Kruskal’s algorithm and the Union-Find traversal in Step 3 take \(O((N + M) \alpha(N))\) where \(\alpha\) is the inverse Ackermann function, so the sorting is the bottleneck.
  • Space complexity: \(O(N + M)\)
    • The memory required for the adjacency list, Union-Find, and various arrays is proportional to the number of vertices and edges.

Implementation Notes

  • Tree contraction using Union-Find: In Step 3, by finding the representative of parent[curr_u], we can jump directly to “the nearest ancestor that has not yet been updated”.

    p = find_uf(parent[curr_u])
    uf[curr_u] = p # Merge the already-updated vertex into the parent's group
    curr_u = p
    

    With this technique, we effectively contract the tree while traversing it, ensuring fast operation even in the worst case.

    Source Code

import sys

def solve():
    # 入力を一括で読み込むことで高速化
    input_data = sys.stdin.read().split()
    if not input_data:
        return
    
    N = int(input_data[0])
    M = int(input_data[1])
    
    edges = []
    idx = 2
    for i in range(M):
        u = int(input_data[idx]) - 1
        v = int(input_data[idx+1]) - 1
        w = int(input_data[idx+2])
        edges.append((w, u, v, i))
        idx += 3
        
    # 辺をコストの昇順にソート
    edges.sort(key=lambda x: x[0])
    
    # クラスカル法のためのUnion-Find
    parent_kf = list(range(N))
    def find_kf(i):
        path = []
        while parent_kf[i] != i:
            path.append(i)
            i = parent_kf[i]
        for node in path:
            parent_kf[node] = i
        return i
    
    mst_edges = []
    non_mst_edges = []
    mst_cost = 0
    mst_edge_count = 0
    
    for w, u, v, i_idx in edges:
        root_u = find_kf(u)
        root_v = find_kf(v)
        if root_u != root_v:
            parent_kf[root_u] = root_v
            mst_edges.append((w, u, v, i_idx))
            mst_cost += w
            mst_edge_count += 1
        else:
            non_mst_edges.append((w, u, v, i_idx))
            
    if mst_edge_count < N - 1:
        print(-1)
        return

    # 最小全域木 (MST) の隣接リストを構築
    adj = [[] for _ in range(N)]
    for w, u, v, i_idx in mst_edges:
        adj[u].append((v, i_idx, w))
        adj[v].append((u, i_idx, w))
        
    # BFSにより根付き木を構築(頂点0を根とする)
    parent = [-1] * N
    parent_edge_idx = [-1] * N
    parent_edge_cost = [-1] * N
    depth = [0] * N
    
    queue = [0]
    visited = [False] * N
    visited[0] = True
    
    head = 0
    while head < len(queue):
        u = queue[head]
        head += 1
        for v, i_idx, w in adj[u]:
            if not visited[v]:
                visited[v] = True
                parent[v] = u
                parent_edge_idx[v] = i_idx
                parent_edge_cost[v] = w
                depth[v] = depth[u] + 1
                queue.append(v)
                
    # 代替辺を効率よく更新するためのUnion-Find
    uf = list(range(N))
    def find_uf(i):
        path = []
        while uf[i] != i:
            path.append(i)
            i = uf[i]
        for node in path:
            uf[node] = i
        return i

    INF = 10**18
    alt_cost = [INF] * M
    
    # 非MST辺をコストの小さい順に処理し、MST上のパスを更新
    for w, u, v, i_idx in non_mst_edges:
        curr_u = find_uf(u)
        curr_v = find_uf(v)
        while curr_u != curr_v:
            if depth[curr_u] < depth[curr_v]:
                curr_u, curr_v = curr_v, curr_u
            
            edge_idx = parent_edge_idx[curr_u]
            alt_cost[edge_idx] = w
            
            p = find_uf(parent[curr_u])
            uf[curr_u] = p
            curr_u = p
            
    # 各MST辺を取り除いたときの最大コストを計算
    ans = mst_cost
    for i in range(1, N):
        i_idx = parent_edge_idx[i]
        alt = alt_cost[i_idx]
        if alt == INF:
            print(-1)
            return
        cost = mst_cost - parent_edge_cost[i] + alt
        if cost > ans:
            ans = cost
            
    print(ans)

if __name__ == '__main__':
    solve()

This editorial was generated by gemini-3.5-flash-thinking.