Last Updated: 31 Mar, 2026

Minimum Cost to Connect Network

Hard
Asked in company
Amazon

Problem statement

You are the network administrator for a campus with n buildings. A set of cables originally connected all buildings, forming a single connected network. Unfortunately, due to some damage, some of these cables are now broken.


You are given:

  • n: The number of buildings (nodes), numbered 1 to n.
  • edges: A list of all cables that are currently working.
  • broken_edges: A separate list of the broken cables, along with the cost to repair each one.


Your task is to determine the minimum total cost to repair a selection of broken cables so that all n buildings are once again part of a single, fully connected network.


If it's impossible to connect all buildings even after repairing all broken cables, you should report it.


Input Format:
The first line contains an integer n, the number of buildings.

The second line contains an integer e, the number of working edges.

The next e lines each contain two space-separated integers, u and v, representing a working cable between buildings u and v.

The next line contains an integer b, the number of broken edges.

The next b lines each contain three space-separated integers, u, v, and cost, representing a broken cable between u and v with its repair cost.


Output Format:
Your function should return a single integer representing the minimum cost to reconnect the network.

If it's impossible to reconnect the network, your function should return -1.

The runner code will handle printing the returned value.


Notes:
This problem can be modeled as finding a Minimum Spanning Tree (MST) on a graph.