LeetCode 1579 保證圖可完全遍歷
阿新 • • 發佈:2021-02-15
LeetCode 1579 保證圖可完全遍歷
Alice 和 Bob 共有一個無向圖,其中包含 n 個節點和 3 種類型的邊:
- 型別 1:只能由 Alice 遍歷。
- 型別 2:只能由 Bob 遍歷。
- 型別 3:Alice 和 Bob 都可以遍歷。
給你一個數組 edges ,其中 edges[i] = [typei, ui, vi] 表示節點 ui 和 vi 之間存在型別為 typei 的雙向邊。請你在保證圖仍能夠被 Alice和 Bob 完全遍歷的前提下,找出可以刪除的最大邊數。如果從任何節點開始,Alice 和 Bob 都可以到達所有其他節點,則認為圖是可以完全遍歷的。
返回可以刪除的最大邊數,如果 Alice 和 Bob 無法完全遍歷圖,則返回 -1 。
示例 1:
輸入:n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]
輸出:2
解釋:如果刪除 [1,1,2] 和 [1,1,3] 這兩條邊,Alice 和 Bob 仍然可以完全遍歷這個圖。再刪除任何其他的邊都無法保證圖可以完全遍歷。所以可以刪除的最大邊數是 2 。
示例 2:
輸入:n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]] 輸出:0 解釋:注意,刪除任何一條邊都會使 Alice 和 Bob 無法完全遍歷這個圖。
示例 3:
輸入:n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]
輸出:-1
解釋:在當前圖中,Alice 無法從其他節點到達節點 4 。類似地,Bob 也不能達到節點 1 。因此,圖無法完全遍歷。
這題就是比較簡單的並查集,我們分別對兩個人建立一個並查集,先刪公共邊中的累贅邊,再分別刪各自獨佔邊中的累贅邊即可,AC程式碼如下:
class Unionset {
public:
vector<int> father;
vector<int> sum;
int cnt = 0;
public:
void init(int n) {
father.resize(n);
for (int i = 0; i < n; i++) father[i] = i;
sum.resize(n);
cnt = n;
}
int findFather(int x) {
return x == father[x] ? x : father[x] = findFather(father[x]);
}
bool Union(int x, int y) {
x = findFather(x), y = findFather(y);
if (x == y) return 0;
if (sum[x] < sum[y]) swap(x, y);
father[y] = x;
sum[x] += sum[y];
--cnt;
return 1;
}
};
class Solution {
public:
int maxNumEdgesToRemove(int n, vector<vector<int>> &edges) {
Unionset a = Unionset();
Unionset b = Unionset();
int ans = 0;
a.init(n);
b.init(n);
for (auto &i:edges) --i[1], --i[2];
for (auto &i:edges) {
if (i[0] == 3) {
if (!a.Union(i[1], i[2])) ans++;
else b.Union(i[1], i[2]);
}
}
for (auto &i:edges) {
if (i[0] == 1) {
if (!a.Union(i[1], i[2])) ans++;
}
if (i[0] == 2) {
if (!b.Union(i[1], i[2])) ans++;
}
}
if (a.cnt != 1 || b.cnt != 1) return -1;
return ans;
}
};