题目来源
题目描述
class Solution {
public:
bool equationsPossible(vector<string>& equations) {
}
};
题目解析
题意
- 给了一系列简单的公式,某两个字母相等或者不等,然后问给的这些公式会不会产生矛盾
并查集
思路
- 合并相等的项
- 从不相等里面找冲突
class Solution {
class UnionFind{
private:
int cnt;
std::vector<int> parent;
std::vector<int> weight;
std::vector<int> help;
public:
explicit UnionFind(int n){
this->cnt = n;
parent.resize(n);
weight.resize(n);
help.resize(n);
for (int i = 0; i < n; ++i) {
parent[i] = i;
weight[i] = 1;
}
}
int count() const{
return cnt;
}
void merge(int p, int q){
int rootP = findRoot(p);
int rootQ = findRoot(q);
if(rootP == rootQ){
return;
}
// ⼩树接到⼤树下⾯, 较平衡
if(weight[rootP] > weight[rootQ]){
parent[rootQ] = rootP;
weight[rootP] += weight[rootQ];
}else{
parent[rootP] = rootQ;
weight[rootQ] += weight[rootP];
}
--cnt;
}
bool isConnected(int p, int q){
int rootP = findRoot(p);
int rootQ = findRoot(q);
return rootP == rootQ;
}
private:
int findRoot(int x){
int hi = 0;
while (parent[x] != x){
help[hi++] = x;
x = parent[x];
}
for (hi--; hi >= 0; --hi) {
parent[help[hi]] = x;
}
return x;
}
};
public:
bool equationsPossible(vector<string>& equations) {
UnionFind uf(26);
for(auto eq : equations){
if(eq[1] == '!'){
continue;
}
uf.merge(eq[0] - 'a', eq[0] - 'a');
}
for(auto eq : equations){
if(eq[1] == '='){
continue;
}
if(uf.isConnected(eq[3] - 'a', eq[3] - 'a')){
return false;
}
}
return true;
}
};
无向图
class Solution {
bool isConnected(unordered_map<char, unordered_set<char>>& g, char cur, char target, unordered_set<char>& visited){
if (cur == target || g[cur].count(target))
return true;
for (char c : g[cur]) {
if (visited.count(c))
continue;
visited.insert(c);
if (!isConnected(g, c, target, visited))
return true;
}
return false;
}
public:
bool equationsPossible(vector<string>& equations) {
unordered_map<char, unordered_set<char>> g;
for(auto eq : equations){
if(eq[1] == '!'){
continue;
}
g[eq[0]].insert(eq[3]);
g[eq[3]].insert(eq[0]);
}
for(auto eq : equations){
if(eq[1] == '='){
continue;
}
unordered_set<char> visited;
if (isConnected(g, eq[0], eq[3], visited))
return false;
}
return true;
}
};
类似题目
题目 | 思路 |
---|---|
leetcode:200. 岛屿数量 Number of Islands | dfs、并查集 |
leetcode:261. 以图判树 Graph Valid Tree | |
leetcode:990. 等式方程的可满足性 Satisfiability of Equality Equations | |
leetcode:685. 冗余连接 II Redundant Connection II |