forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
satisfiability-of-equality-equations.cpp
105 lines (96 loc) · 2.67 KB
/
satisfiability-of-equality-equations.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
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Time: O(n)
// Space: O(1)
class Solution {
public:
bool equationsPossible(vector<string>& equations) {
UnionFind union_find(26);
for (const auto& eqn : equations) {
int x = eqn[0] - 'a';
int y = eqn[3] - 'a';
if (eqn[1] == '=') {
union_find.union_set(x, y);
}
}
for (const auto& eqn : equations) {
int x = eqn[0] - 'a';
int y = eqn[3] - 'a';
if (eqn[1] == '!') {
if (union_find.find_set(x) == union_find.find_set(y)) {
return false;
}
}
}
return true;
}
private:
class UnionFind {
public:
UnionFind(const int n) : set_(n) {
iota(set_.begin(), set_.end(), 0);
}
int find_set(const int x) {
if (set_[x] != x) {
set_[x] = find_set(set_[x]); // Path compression.
}
return set_[x];
}
bool union_set(const int x, const int y) {
int x_root = find_set(x), y_root = find_set(y);
if (x_root == y_root) {
return false;
}
set_[min(x_root, y_root)] = max(x_root, y_root);
return true;
}
private:
vector<int> set_;
};
};
// Time: O(n)
// Space: O(1)
class Solution2 {
public:
bool equationsPossible(vector<string>& equations) {
vector<vector<int>> graph(26);
for (const auto& eqn : equations) {
int x = eqn[0] - 'a';
int y = eqn[3] - 'a';
if (eqn[1] == '!') {
if (x == y) {
return false;
}
} else {
graph[x].emplace_back(y);
graph[y].emplace_back(x);
}
}
vector<int> color(26);
for (int i = 0, c = 0; i < color.size(); ++i) {
if (color[i]) {
continue;
}
++c;
vector<int> stack = {c};
while (!stack.empty()) {
int node = stack.back(); stack.pop_back();
for (const auto& nei : graph[node]) {
if (!color[nei]) {
color[nei] = c;
stack.emplace_back(nei);
}
}
}
}
for (const auto& eqn : equations) {
if (eqn[1] != '!') {
continue;
}
int x = eqn[0] - 'a';
int y = eqn[3] - 'a';
if (color[x] && color[x] == color[y]) {
return false;
}
}
return true;
}
};