LeetCode——2285. Maximum Total Importance of Roads(C++)

LeetCode——2285. Maximum Total Importance of Roads(C++)
Description:
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.
Example 1:
在这里插入图片描述
Input: n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]
Output: 43
Explanation: The figure above shows the country and the assigned values of [2,4,5,3,1].

  • The road (0,1) has an importance of 2 + 4 = 6.
  • The road (1,2) has an importance of 4 + 5 = 9.
  • The road (2,3) has an importance of 5 + 3 = 8.
  • The road (0,2) has an importance of 2 + 5 = 7.
  • The road (1,3) has an importance of 4 + 3 = 7.
  • The road (2,4) has an importance of 5 + 1 = 6.
    The total importance of all roads is 6 + 9 + 8 + 7 + 7 + 6 = 43.
    It can be shown that we cannot obtain a greater total importance than 43.
    Example 2:
    在这里插入图片描述
    Input: n = 5, roads = [[0,3],[2,4],[1,3]]
    Output: 20
    Explanation: The figure above shows the country and the assigned values of [4,3,2,5,1].
  • The road (0,3) has an importance of 4 + 5 = 9.
  • The road (2,4) has an importance of 2 + 1 = 3.
  • The road (1,3) has an importance of 3 + 5 = 8.
    The total importance of all roads is 9 + 3 + 8 = 20.
    It can be shown that we cannot obtain a greater total importance than 20.

Constraints:
2 <= n <= 5 * 104
1 <= roads.length <= 5 * 104
roads[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
There are no duplicate roads.

题目解析:
看似图题,但更像数组题,计算一下各个点的度,排序后乘以对应的系数,就可以了。

代码:

class Solution {
public:
    long long maximumImportance(int n, vector<vector<int>>& roads) {
        if(roads.size()==0)return 0;
        vector<long long>cnt;
        cnt.resize(n);
        for(int i=0;i<roads.size();i++)
        {
            int j,k;
            j=roads[i][0];
            k=roads[i][1];
            cnt[j]++;               //记录每个点的度;
            cnt[k]++;
        }
        sort(cnt.begin(),cnt.end());      
        long long sum=0;
        for(int i=n-1,nums=n;i>=0&&cnt[i]!=0;i--,nums--)   //到度为零的就不需要再继续遍历了
            sum+=cnt[i]*nums;
        return sum;
    }
};

Submission:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值