[LeetCode] Maximum Total Importance of Roads

2285. Maximum Total Importance of Roads

You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1.

You are also given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi.

You need to assign each city with an integer value from 1 to n, where each value can only be used once. The importance of a road is then defined as the sum of the values of the two cities it connects.

Return the maximum total importance of all roads possible after assigning the values optimally.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
long long maximumImportance(int n, vector<vector<int>>& roads) {
vector<long long> conn(n), w(n);
for(auto& r : roads) {
int u = r[0], v = r[1];
conn[u]++;
conn[v]++;
}
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
for(int i = 0; i < n; i++) {
pq.push({conn[i], i});
}
for(int i = 1; i <= n; i++) {
auto [_, u] = pq.top(); pq.pop();
w[u] = i;
}
long long res = 0;
for(auto& r : roads) {
int u = r[0], v = r[1];
res += w[u] + w[v];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/29/PS/LeetCode/maximum-total-importance-of-roads/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.