Loading...
Loading...
You are given n cities numbered 0 to n - 1, a list of candidate roads roads, and two integers hubCost and roadCost. Each element in roads contains [u, v] meaning a two-way road can be built between cities u and v.
Nothing is built at the start. Building a hub in a city costs hubCost. Building one road from roads costs roadCost.
A city is covered if it has a hub, or if it can reach a city with a hub by traveling only along built roads.
Return the minimum total cost to cover every city.
Note that only roads from roads can be built. The same pair of cities may appear in roads more than once.
Input: n = 4
roads = [[0, 1],
[1, 2],
[2, 0],
[2, 3]]
hubCost = 5
roadCost = 2
Output: 11
Explanation: Build a hub in city 2 (cost 5) and build the roads [0,1], [1,2], and [2,3] (cost 2 each).
Every city can now reach city 2, so the total is 5 + 3 * 2 = 11. The road [2,0] is not needed.
Input: n = 3
roads = [[0, 1],
[1, 2]]
hubCost = 1
roadCost = 3
Output: 3
Explanation: Build a hub in every city and no roads: 3 * 1 = 3.
Covering any city through a road instead of its own hub would cost 3 instead of 1.
Input: n = 5
roads = [[0, 1],
[1, 2],
[3, 1]]
hubCost = 4
roadCost = 1
Output: 11
Explanation: Build a hub in city 1 and all three roads, so cities 0, 1, 2, and 3 are covered for 4 + 3 * 1 = 7.
No road touches city 4, so it needs its own hub for 4 more. The total is 7 + 4 = 11.
roads.length ≤105roads[i] = [u, v] with 0≤u,v<n and u=vhubCost, roadCost ≤104