../ Competitive Programming
-rw-r--r--aguang828 B1 min read

modified

Leet Code Daily 2024-06-28 - Maximum Total Importance of Roads

Solution

Greedy.

The total importance of all roads is:

∑i∈nodesvaluei×degreei\sum_{i \in \text{nodes}} \text{value}_i \times \text{degree}_i

Obviously, node with bigger degree should always be assigned with bigger value.

Code

c++
class Solution {
public:
    long long maximumImportance(int n, vector<vector<int>>& roads) {

        vector<int> degree(n, 0);
        for (const auto& road : roads) {
            degree[road[0]]++;
            degree[road[1]]++;
        }

        sort(degree.begin(), degree.end());

        long long ret = 0;
        for (int i = 0; i < n; i++) {
            ret += (long long)(i + 1) * degree[i];
        }
        return ret;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window