forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
67 lines (49 loc) · 1.21 KB
/
main2.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
/// Source : https://leetcode.com/problems/satisfiability-of-equality-equations/
/// Author : liuyubobobo
/// Time : 2019-02-09
#include <iostream>
#include <vector>
using namespace std;
/// Using Union-Found
/// Time Complexity: O(n)
/// Space Complexity: O(26)
class UF{
private:
vector<int> parent;
public:
UF(int n){
for(int i = 0 ; i < n ; i ++)
parent.push_back(i);
}
int find(int p){
if( p != parent[p] )
parent[p] = find( parent[p] );
return parent[p];
}
bool isConnected(int p , int q){
return find(p) == find(q);
}
void unionElements(int p, int q){
int pRoot = find(p);
int qRoot = find(q);
if( pRoot == qRoot )
return;
parent[pRoot] = qRoot;
}
};
class Solution {
public:
bool equationsPossible(vector<string>& equations) {
UF uf(26);
for(const string& e: equations)
if(e[1] == '=')
uf.unionElements(e[0] - 'a', e[3] - 'a');
for(const string& e: equations)
if(e[1] == '!' && uf.isConnected(e[0] - 'a', e[3] - 'a'))
return false;
return true;
}
};
int main() {
return 0;
}