ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

990. 等式方程的可满足性

2020-04-23 22:57:20  阅读:302  来源: 互联网

标签:方程 990 parent int eq 等式 rootQ rootP size


 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 };

 

标签:方程,990,parent,int,eq,等式,rootQ,rootP,size
来源: https://www.cnblogs.com/yuhong1103/p/12764385.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有