Back to challenges
Hard 0 solved 0% acceptance

Minimum Network Connection Cost

Choose undirected links so that every vertex can reach every other vertex, with minimum total cost.

What you'll learn

  • Connect a graph cheaply with Kruskal's algorithm
  • Detect cycles with a disjoint-set union
  • Report when a graph cannot be connected

Problem

Choose undirected links so that every vertex can reach every other vertex, with minimum total cost. A link can be used in either direction. Return −1 if the available links cannot connect the whole network. You do not need to return the selected links.

Implement minimum_network_connection_cost(vertices, links).

Input

vertices: The number of network vertices.

links: Available links [u, v, cost].

Output

Return the minimum total cost, −1 if impossible, or 0 for a one-vertex network.

Constraints

1 ≤ vertices ≤ 100,000. 0…200,000 links; endpoints are distinct vertices in 1…vertices. Costs are 1…1,000,000,000. Parallel links are allowed. The total fits signed 64-bit.

Examples

Example 1
Input:
links = [
    [1, 2, 4],
    [2, 3, 2],
    [1, 3, 7]
]
vertices = 3

Expected output:
expected = 6
Input:
std::vector<std::vector<long long>> links = {
    {1, 2, 4},
    {2, 3, 2},
    {1, 3, 7}
};
long long vertices = 3;

Expected output:
long long expected = 6;
Input:
long[][] links = new long[][] {
    new long[] {1, 2, 4},
    new long[] {2, 3, 2},
    new long[] {1, 3, 7}
};
long vertices = 3;

Expected output:
long expected = 6;

Explanation

Choose links costing 4 and 2 to connect all three vertices. Their total is 6; the cost-7 link is unnecessary.

Example 2
Input:
links = [
    [1, 2, 4]
]
vertices = 3

Expected output:
expected = -1
Input:
std::vector<std::vector<long long>> links = {
    {1, 2, 4}
};
long long vertices = 3;

Expected output:
long long expected = -1;
Input:
long[][] links = new long[][] {
    new long[] {1, 2, 4}
};
long vertices = 3;

Expected output:
long expected = -1;

Explanation

Vertex 3 has no connection. No selection can connect the entire network.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

You need a cheapest set of links that still keeps every vertex connected, which suggests a spanning tree.

Hint 2

Greedily add the cheapest link that does not create a cycle, or grow components with a union-find structure.

Hint 3

If fewer than vertices minus one usable links connect the graph, the answer is impossible.

Expected complexity

O(links log links) time, O(vertices + links) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.