Problem Description
We are given n cities (numbered from 0 to n - 1) and a list of bidirectional roads connecting these cities. We need to assign each city a unique value from 1 to n. The importance of a road is the sum of the values assigned to the two cities it connects. Our goal is to maximize the total importance of all roads after an optimal assignment.
Key Insights
- The contribution of a city to the total importance is proportional to its degree (the number of roads connected to that city).
- To maximize the total importance, assign higher values to cities with higher degrees.
- The overall maximum importance can be computed as the sum for all cities of (assigned value * city degree).
- Greedy strategy: sort cities by degree and assign values in descending order from n to 1.
Space and Time Complexity
Time Complexity: O(n + m + n log n)
- O(n) to initialize and count degrees.
- O(m) to process the roads.
- O(n log n) to sort the cities by their degree. Space Complexity: O(n)
- We store the degree for each of the n cities.
Solution
We begin by calculating the degree for each city based on the given roads. Once we have the degree counts, we sort the cities by their degrees in ascending order. Then we assign the highest value (n) to the city with the highest degree, the next highest (n - 1) to the city with the second highest degree, and so on. Finally, we compute the total importance by multiplying each city’s degree with the assigned value and summing up these products. This greedy assignment ensures that cities contributing more (with higher degrees) receive higher values, maximizing the overall sum.