Last Updated: 8 Sep, 2025

Redundant Network Design

Ninja
Asked in company
Zeta

Problem statement

You are given an undirected, weighted graph representing a network of servers, with 'V' servers and a list of potential connections. Each connection [u, v, w] represents a cable that can be laid between server u and server v with a cost of w.

Your primary goal is to build the cheapest possible network that connects all servers. This is known as the Minimum Spanning Tree (MST).

However, for reliability, you also need to find the second-best MST. The second-best MST is a spanning tree whose total cost is the next-smallest possible value that is strictly greater than the cost of the first MST. It is known that any second-best MST can be formed from an MST by swapping one of its edges with one of the graph's edges not in the MST.

Your task is to calculate and return the total cost of the second-best MST.


Input Format:
The first line of input contains two space-separated integers, 'V' and 'E', the number of vertices and edges.
The next 'E' lines each contain three space-separated integers, u, v, and w, representing an undirected edge between u and v with weight w.


Output Format:
Print a single integer representing the cost of the second-best MST.
If no second-best MST exists (e.g., the graph is already a tree), print -1.
Note:
The algorithm to solve this is:
1)Find the first MST and its total cost using an algorithm like Kruskal's. Keep a list of the edges that are part of this MST.
2)Iterate through every edge (u, v) with weight w_new that was not included in the first MST.
3)For each such edge, temporarily adding it to the MST creates a unique cycle. To form a new spanning tree, we must remove another edge from this cycle.
4)To find the smallest increase in cost, we must remove the heaviest edge on the path between u and v within the first MST.
5)Calculate the new tree's cost: MST_cost + w_new - w_heaviest.
6)The second-best MST cost is the minimum of these calculated costs that is strictly greater than the original MST cost.