-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1579. Remove max number of edges to keep graph fully traversable
77 lines (60 loc) · 1.96 KB
/
1579. Remove max number of edges to keep graph fully traversable
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//1579. Remove max number of edges to keep graph fully traversable
class Solution {
public int maxNumEdgesToRemove(int n, int[][] edges) {
Arrays.sort(edges, (a, b) -> b[0] - a[0]);
int edgeAdd = 0;
UnionFind alice = new UnionFind(n);
UnionFind bob = new UnionFind(n);
for(int[] edge : edges) {
int type = edge[0];
int a = edge[1];
int b = edge[2];
switch(type) {
case 3:
if(alice.unite(a, b) | bob.unite(a, b)) {
edgeAdd++;
}
break;
case 2:
if(bob.unite(a, b)) {
edgeAdd++;
}
break;
case 1:
if(alice.unite(a, b)) {
edgeAdd++;
}
break;
}
}
return (alice.united() && bob.united()) ? edges.length - edgeAdd : -1;
}
private class UnionFind {
int[] component;
int distinctComponents;
public UnionFind(int n) {
component = new int[n + 1];
for(int i = 0; i <= n; i++) {
component[i] = i;
}
distinctComponents = n;
}
private boolean unite(int a, int b) {
if(findComponent(a) != findComponent(b)) {
component[findComponent(a)] = b;
distinctComponents--;
return true;
}
return false;
}
private int findComponent(int a) {
if(component[a] != a) {
component[a] = findComponent(component[a]);
}
return component[a];
}
private boolean united() {
return distinctComponents == 1;
}
}
}