[LeetCode] Remove Max Number of Edges to Keep Graph Fully Traversable

1579. Remove Max Number of Edges to Keep Graph Fully Traversable

Alice and Bob have an undirected graph of n nodes and 3 types of edges:

  • Type 1: Can be traversed by Alice only.
  • Type 2: Can be traversed by Bob only.
  • Type 3: Can by traversed by both Alice and Bob.

Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes.

Return the maximum number of edges you can remove, or return -1 if it’s impossible for the graph to be fully traversed by Alice and Bob.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
int find(vector<int>& g, int n) {
return g[n] == n ? n : g[n] = find(g, g[n]);
}
void uni(vector<int>& g, int a, int b) {
int pa = find(g, a), pb = find(g, b);
g[pa] = g[pb] = min(pa, pb);
}
public:
int maxNumEdgesToRemove(int n, vector<vector<int>>& edges) {
vector<int> common(n), alice, bob;
vector<vector<vector<int>>> e(2,vector<vector<int>>());
for(int i = 0; i < n; i++) common[i] = i;
int res = 0;
for(auto edge : edges) {
if(edge[0] == 1) e[0].push_back({edge[1] - 1,edge[2] - 1});
else if(edge[0] == 2) e[1].push_back({edge[1] - 1,edge[2] - 1});
else {
int pa = find(common, edge[1] - 1), pb = find(common,edge[2] - 1);
if(pa == pb) res++;
else uni(common,pa,pb);
}
}
alice = bob = common;
for(auto edge : e[0]) {
int pa = find(alice, edge[0]), pb = find(alice, edge[1]);
if(pa == pb) res++;
else uni(alice, pa, pb);
}

for(auto edge : e[1]) {
int pa = find(bob, edge[0]), pb = find(bob, edge[1]);
if(pa == pb) res++;
else uni(bob, pa, pb);
}

int sum = 0;
for(int i = 0; i < n and !sum; i++) {
sum += find(alice,i) + find(bob,i);
}

return sum ? -1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/26/PS/LeetCode/remove-max-number-of-edges-to-keep-graph-fully-traversable/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.