3.15 Leetcode: 1615. Maximal Network Rank

There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi.

The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once.

The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities.

Given the integer n and the array roads, return the maximal network rank of the entire infrastructure.

思路:

最大网络秩是与两个城市直接相连的道路总数的最大值

定义一个邻接矩阵nb 表示 两个节点是否相连 相连为1 不相连为0

网络秩 = i节点相连的道路 + j节点相连的道路 - nb[i][j]  (遍历更新)

代码:

class Solution {
public:
    int maximalNetworkRank(int n, vector<vector<int>>& roads) {
        vector<vector<int>> nb(n, vector<int>(n, 0));
        vector<int> cnt(n);
        for(auto r: roads) {
            nb[r[0]][r[1]] = 1;
            nb[r[1]][r[0]] = 1;
            cnt[r[0]]++;
            cnt[r[1]]++;
        }
        int res = INT_MIN;
        for(int i = 0; i < n; i++) {
            for(int j = i + 1; j < n; j++) {
                res = max(res, cnt[i] + cnt[j] - nb[i][j]);
            }
        }
        return res;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值