990. 等式方程的可满足性(并查集)
990. 等式方程的可满足性难度中等
给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 equations[i]
的长度为 4
,并采用两种不同的形式之一:"a==b"
或 "a!=b"
。在这里,a 和 b 是小写字母(不一定不同),表示单字母变量名。
只有当可以将整数分配给变量名,以便满足所有给定的方程时才返回 true
,否则返回 false
。
示例 1:
输入:["a==b","b!=a"] 输出:false 解释:如果我们指定,a = 1 且 b = 1,那么可以满足第一个方程,但无法满足第二个方程。没有办法分配变量同时满足这两个方程。
示例 2:
输入:["b==a","a==b"] 输出:true 解释:我们可以指定 a = 1 且 b = 1 以满足满足这两个方程。
示例 3:
输入:["a==b","b==c","a==c"] 输出:true
示例 4:
输入:["a==b","b!=c","c==a"] 输出:false
示例 5:
输入:["c==c","b==d","x!=z"] 输出:true
提示:
1 <= equations.length <= 500
equations[i].length == 4
equations[i][0]
和equations[i][3]
是小写字母equations[i][1]
要么是'='
,要么是'!'
equations[i][2]
是'='
1 constexpr int SIZE = 26; 2 class UnionFind { 3 public: 4 int id[SIZE]; // 存储a~z字符的父亲节点 5 UnionFind() { 6 // 初始化26个字符索引存储的父节点均指向自己 7 for (int i = 0; i < SIZE; i++) { 8 id[i] = i; 9 } 10 } 11 // 合并两个元素到同一集合 12 void unify(int x, int y) { 13 if (isConnected(x, y)) { 14 return; 15 } 16 int xRoot = findRoot(x); 17 int yRoot = findRoot(y); 18 if (xRoot < yRoot) { 19 id[xRoot] = yRoot; 20 } else { 21 id[yRoot] = xRoot; 22 } 23 return; 24 } 25 int findRoot(int x) { 26 int root = x; 27 while (root != id[root]) { 28 root = id[root]; 29 } 30 while (x != root) { 31 int next = id[x]; 32 id[x] = root; 33 x = next; 34 } 35 return root; 36 } 37 bool isConnected(int x, int y) { 38 return (findRoot(x) == findRoot(y)); 39 } 40 }; 41 class Solution { 42 public: 43 UnionFind unionFind; 44 bool equationsPossible(vector<string>& equations) { 45 for (auto &str : equations) { 46 // 合并等式两边的字符到同一个集合中 47 if (str[1] == '=') { 48 int index1 = str[0] - 'a'; 49 int index2 = str[3] - 'a'; 50 unionFind.unify(index1, index2); 51 } 52 } 53 for (auto &str : equations) { 54 // 判定不等式两边元素是否在同一集合中,如果在同一集合中则矛盾,返回false 55 if (str[1] == '!') { 56 int index1 = str[0] - 'a'; 57 int index2 = str[3] - 'a'; 58 if (unionFind.isConnected(index1, index2)) { 59 return false; 60 } 61 } 62 } 63 return true; 64 } 65 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了