-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0886-possible-bipartition.cpp
47 lines (42 loc) · 1.22 KB
/
0886-possible-bipartition.cpp
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 UnionFind {
private:
vector<int> parent, rank;
public:
UnionFind(int size) {
parent.resize(size);
rank.resize(size, 0);
for (int i = 0; i < size; i++)
parent[i] = i;
}
int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
void union_set(int x, int y) {
int xset = find(x), yset = find(y);
if (xset == yset) return;
else if (rank[xset] < rank[yset]) parent[xset] = yset;
else if (rank[xset] > rank[yset]) parent[yset] = xset;
else {
parent[yset] = xset;
rank[xset]++;
}
}
};
class Solution {
public:
bool possibleBipartition(int n, vector<vector<int>>& dislikes) {
vector<vector<int>> adj(n + 1);
for (auto& dislike : dislikes) {
adj[dislike[0]].push_back(dislike[1]);
adj[dislike[1]].push_back(dislike[0]);
}
UnionFind dsu(n + 1);
for (int node = 1; node <= n; node++)
for (int neighbor : adj[node]) {
if (dsu.find(node) == dsu.find(neighbor)) return false;
dsu.union_set(adj[node][0], neighbor);
}
return true;
}
};