forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPossible Bipartition.java
47 lines (47 loc) · 1.21 KB
/
Possible Bipartition.java
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
class Solution {
int[] rank;
int[] parent;
int[] rival;
public boolean possibleBipartition(int n, int[][] dislikes) {
rank = new int[n+1];
rival = new int[n+1];
parent = new int[n+1];
for(int i = 1;i <= n;i++){
rank[i] = 1;
parent[i] = i;
}
for(int[] dis : dislikes){
int x = dis[0], y = dis[1];
if(find(x) == find(y))
return false;
if(rival[x] != 0)
union(rival[x], y);
else
rival[x] = y;
if(rival[y] != 0)
union(rival[y], x);
else
rival[y] = x;
}
return true;
}
public int find(int x){
if(parent[x] == x)
return x;
return parent[x] = find(parent[x]);
}
public void union(int x, int y){
int x_set = find(x);
int y_set = find(y);
if(x_set == y_set)
return;
if(rank[x_set] < rank[y_set])
parent[x_set] = y_set;
else if(rank[y_set] < rank[x_set])
parent[y_set] = x_set;
else{
parent[x_set] = y_set;
rank[y_set]++;
}
}
}