990. 等式方程的可满足性

 1 class UF 
 2 {
 3 public:
 4     int count; // 记录连通分量个数
 5     vector<int> parent; // 存储若干棵树
 6     vector<int> size; // 记录树的“重量”
 7 
 8     UF(int n) 
 9     {
10         count = n;
11         parent = vector<int>(n);
12         size = vector<int>(n);
13         for (int i = 0; i < n; i++) 
14         {
15             parent[i] = i;
16             size[i] = 1;
17         }
18     }
19 
20     /* 将 p 和 q 连通 */
21     void Union(int p, int q) 
22     {
23         int rootP = find(p);
24         int rootQ = find(q);
25         if (rootP == rootQ) return;
26 
27         // 小树接到大树下面,较平衡
28         if (size[rootP] > size[rootQ]) 
29         {
30             parent[rootQ] = rootP;
31             size[rootP] += size[rootQ];
32         } 
33         else 
34         {
35             parent[rootP] = rootQ;
36             size[rootQ] += size[rootP];
37         }
38         count--;
39     }
40 
41     /* 判断 p 和 q 是否互相连通 */
42     bool connected(int p, int q) 
43     {
44         int rootP = find(p);
45         int rootQ = find(q);
46         // 处于同一棵树上的节点,相互连通
47         return rootP == rootQ;
48     }
49 
50     /* 返回节点 x 的根节点 */
51     int find(int x) 
52     {
53         while (parent[x] != x) // 进行路径压缩
54         {
55             parent[x] = parent[parent[x]];
56             x = parent[x];
57         }
58         return x;
59     }
60 
61     int Count() 
62     {
63         return count;
64     }
65 };
66 
67 class Solution 
68 {
69 public:
70     bool equationsPossible(vector<string>& equations) 
71     {
72         // 26 个英文字母
73         UF uf(26);
74         // 先让相等的字母形成连通分量
75         for (auto eq : equations) 
76         {
77             if (eq[1] == '=') 
78             {
79                 char x = eq[0];
80                 char y = eq[3];
81                 uf.Union(x - 'a', y - 'a');
82             }
83         }
84         // 检查不等关系是否打破相等关系的连通性
85         for (auto eq : equations) 
86         {
87             if (eq[1] == '!') 
88             {
89                 char x = eq[0];
90                 char y = eq[3];
91                 // 如果相等关系成立,就是逻辑冲突
92                 if (uf.connected(x - 'a', y - 'a')) return false;
93             }
94         }
95         return true;
96     }
97 };

 

上一篇:Python之打印变量


下一篇:微软面试题:LeetCode. 547. 省份数量 middle 出现次数:1 并查集