C++刷LeetCode(1579. 保证图可完全遍历)【并查集】【图】
题目描述:Alice 和 Bob 共有一个无向图,其中包含 n 个节点和 3 种类型的边:
类型 1:只能由 Alice 遍历。
类型 2:只能由 Bob 遍历。
类型 3:Alice 和 Bob 都可以遍历。
给你一个数组 edges ,其中 edges = 表示节点 ui 和 vi 之间存在类型为 typei 的双向边。请你在保证图仍能够被 Alice和 Bob 完全遍历的前提下,找出可以删除的最大边数。如果从任何节点开始,Alice 和 Bob 都可以到达所有其他节点,则认为图是可以完全遍历的。
返回可以删除的最大边数,如果 Alice 和 Bob 无法完全遍历图,则返回 -1 。
示例 1:
输入:n = 4, edges = [,,,,,]
输出:2
解释:如果删除 和 这两条边,Alice 和 Bob 仍然可以完全遍历这个图。再删除任何其他的边都无法保证图可以完全遍历。所以可以删除的最大边数是 2 。
示例 2:
输入:n = 4, edges = [,,,]
输出:0
解释:注意,删除任何一条边都会使 Alice 和 Bob 无法完全遍历这个图。
示例 3:
输入:n = 4, edges = [,,]
输出:-1
解释:在当前图中,Alice 无法从其他节点到达节点 4 。类似地,Bob 也不能达到节点 1 。因此,图无法完全遍历。
提示:
1 <= n <= 10^5
1 <= edges.length <= min(10^5, 3 * n * (n-1) / 2)
edges.length == 3
1 <= edges <= 3
1 <= edges < edges <= n
所有元组 (typei, ui, vi) 互不相同
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
private:
vector<int>father1;
vector<int>father2;
public:
int find_root(int x, vector<int>& par){
int root = x;
while(par!=root){
root = par;
}
while(par!=root){
int tmp = par;
par = root;
x = tmp;
}
return root;
}
bool merge(int x, int y, vector<int>& father){
int temp1 = find_root(x, father);
int temp2 = find_root(y, father);
if(temp1 != temp2){
father = temp2;
return true;
}
return false;
}
int maxNumEdgesToRemove(int n, vector<vector<int>>& edges) {
//并查集
//初始化father
father1 = vector<int>(n+1, 0);
for(int i = 1; i <= n; i++){
father1 = i;
}
int res = 0;
int node1_nums = 1;
//先合并第三种边
for(auto cha : edges){
if(cha == 3){
if(!merge(cha, cha, father1)){
//没有合并
res++;
}else{
//合并了
node1_nums++;
}
}
}
father2 = father1;
int node2_nums = node1_nums;
//合并前两种边
for(auto cha : edges){
if(cha == 1){
if(!merge(cha, cha, father1)){
//没有合并
res++;
}else{
node1_nums++;
}
}else if(cha == 2){
if(!merge(cha, cha, father2)){
res++;
}else{
node2_nums++;
}
}
}
if(node1_nums != n || node2_nums != n)return -1;
return res;
}
};
参考链接:https://leetcode-cn.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable/solution/bing-cha-ji-zheng-ming-zui-zhong-di-san-chong-lei-/
https://leetcode-cn.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable/solution/python-dong-hua-xian-kan-alicezai-kan-bo-kavo/
页:
[1]