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;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_44189622/article/details/129597369