We can think of countries as minimum-spanning trees (MST), cities as nodes, and roads as edges in the graph. Then we can rephrase the problem as building CC disconnected MST using NN nodes and EE in a way so that the maximum cost among minimum spanning trees is the minimum possible.

Iterative Solution:

At first, we will pre-compute and store the cost of MST for every possible subset of cities if these cities are connected otherwise the cost will be stored as INFINF. Let’s define mstCost[sset]mstCost[sset] as the cost of the minimum spanning tree of the subset ssetsset of cities.

Finally, we will use dynamic programming with bitmask to distribute the cities among countries. Let’s suppose, dp[c][mask]dp[c][mask] denotes the minimized maximum cost to distribute a subset maskmask of cities among first CC countries. Now, for the CthC’th country, we will enumerate all sub-masks submasksubmask of mask maskmask. Then, we will calculate the minimum possible maximum cost for the first CC countries as follows:

dp[c][mask]=min(dp[c][mask],max(mstCost[submask],dp[c1][masksubmask])dp[c][mask] = min(dp[c][mask], max(mstCost[submask], dp[c-1][mask-submask])

Time Complexity:

Overall time complexity is C3N+N22NC* 3^N + N^2 * 2^N.

We will require 3N3^N to iterate through all masks with their sub-masks. And we will also require N22NN^2 * 2^N to pre-compute the cost of MST for all possible subsets of cities.

Memory Complexity:

Overall memory complexity is O(C2N)O(C*2^N).

Contributors

Statistics

83% Solution Ratio
Amd_SadiEarliest, Jan '23
Kuddus.6068Fastest, 0.1s
Reckless_RaccoonLightest, 4.9 MB
steinumShortest, 1087B
Toph uses cookies. By continuing you agree to our Cookie Policy.