1615 最大網路秩
阿新 • • 發佈:2021-02-14
技術標籤:LeetCode
題目描述:
n 座城市和一些連線這些城市的道路 roads 共同組成一個基礎設施網路。每個 roads[i] = [ai, bi] 都表示在城市 ai 和 bi 之間有一條雙向道路。
兩座不同城市構成的 城市對 的 網路秩 定義為:與這兩座城市 直接 相連的道路總數。如果存在一條道路直接連線這兩座城市,則這條道路只計算 一次 。
整個基礎設施網路的 最大網路秩 是所有不同城市對中的 最大網路秩 。
給你整數 n 和陣列 roads,返回整個基礎設施網路的 最大網路秩 。
示例 1:
輸入:n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]
解釋:城市 0 和 1 的網路秩是 4,因為共有 4 條道路與城市 0 或 1 相連。位於 0 和 1 之間的道路只計算一次。
示例 2:
輸入:n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]
輸出:5
解釋:共有 5 條道路與城市 1 或 2 相連。
示例 3:
輸入:n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]
輸出:5
解釋:2 和 5 的網路秩為 5,注意並非所有的城市都需要連線起來。
提示:
2 <= n <= 100
0 <= roads.length <= n * (n - 1) / 2
0 <= ai, bi <= n-1
ai != bi
每對城市之間 最多隻有一條 道路相連
方法1:
主要思路:解題連結彙總
(1)統計各個結點直接相連的結點的數量,然後使用數量進行降序排序;
(2)然後儘量使用連線結點更多結點進行統計;
(3)注意最多的連線結點之間是否相連的問題;
class Solution {
public:
int maximalNetworkRank(int n, vector<vector<int>>& roads) {
vector<pair< int,int>> counts(n);
for(int i=0;i<n;++i){
counts[i].second=i;
}
unordered_set<string> st;
for(vector<int>&road:roads){
++counts[road[0]].first;
++counts[road[1]].first;
st.insert(to_string(road[0])+"+"+to_string(road[1]));//雜湊,處理後面判斷結點之間是否相連
}
sort(counts.begin(),counts.end(),[](pair<int,int>&lhs,pair<int,int>&rhs){//使用連線結點的數量進行降序排序
return lhs.first>rhs.first;
});
//最多結點不止一個的情形
if(counts[0].first==counts[1].first){
int res=counts[0].first*2-1;
int end_pos=0;
while(end_pos<n&&counts[end_pos].first==counts[0].first){
++end_pos;
}
for(int i=0;i<end_pos;++i){
for(int j=i+1;j<end_pos;++j){
//是否存在不相連的兩個結點
if(st.count(to_string(counts[i].second)+"+"+to_string(counts[j].second))==0
&&st.count(to_string(counts[j].second)+"+"+to_string(counts[i].second))==0){
return res+1;
}
}
}
return res;
}
else{//最多的結點只有一個的情形
int res=counts[0].first+counts[1].first-1;
int end_pos=1;
while(end_pos<n&&counts[end_pos].first==counts[1].first){
++end_pos;
}
for(int i=1;i<end_pos;++i){
//是否存在不相連的兩個結點
if(st.count(to_string(counts[0].second)+"+"+to_string(counts[i].second))==0
&&st.count(to_string(counts[i].second)+"+"+to_string(counts[0].second))==0){
return res+1;
}
}
return res;
}
return 0;
}
};
方法2:
主要思路:
(1)使用陣列代替相關雜湊關係;
class Solution {
public:
int maximalNetworkRank(int n, vector<vector<int>>& roads) {
vector<vector<bool>> connected(n,vector<bool>(n,false));
vector<int> mp(n,0);
for(vector<int>&road:roads){
++mp[road[0]];
++mp[road[1]];
connected[road[0]][road[1]]=true;
connected[road[1]][road[0]]=true;
}
int res=0;
for(int i=0;i<n;++i){
for(int j=i+1;j<n;++j){
res=max(res,connected[i][j]?mp[i]+mp[j]-1:mp[i]+mp[j]);
}
}
return res;
}
};