Minimum spanning tree · Hard
A service cluster must be wired as one loop-free network. Some links are mandatory because of a signed migration plan. Others are prohibited during the change window. A cheapest unconstrained network can violate either rule.
Return the minimum total cost of a spanning tree that includes every required link and excludes every forbidden link.
Input
Call
- Implement solve(input); return a cost or null, without mutating input.
Network
- n services have IDs 0..n-1. Each link is undirected; parallel links have different indices.
- required and forbidden contain unique valid link indices. The lists do not overlap.
- Required links must be selected even if they cost more than another link.
Output
Feasible network
- Select exactly n-1 links for n > 0, connecting all services without a cycle.
- Include every required index; include no forbidden index.
- Return its minimum cost. Return null if required links form a cycle or allowed links cannot connect all services.
- A required self-link makes the task impossible. With n=0 or n=1 and no required links, return 0.
Constraints
- 0 <= n <= 100000; 0 <= links.length <= 200000.
- Costs are integers in [0,1000000]; all endpoints are valid. No links exist when n=0.
- required.length + forbidden.length <= links.length. Totals fit a JavaScript safe integer.
Examples
Example 1
{
"forbidden": [],
"links": [
[
0,
1,
1
],
[
1,
2,
2
],
[
0,
2,
9
]
],
"n": 3,
"required": [
2
]
}Returns
10The mandatory expensive link changes the optimum.
Example 2
{
"forbidden": [],
"links": [],
"n": 0,
"required": []
}Returns
0Required complexity
O(m log m + n) time and O(n + m) space