当前位置:首页 > 编程笔记 > 正文
已解决

刷题笔记27——并查集

来自网友在路上 151851提问 提问时间:2023-10-09 06:15:50阅读次数: 51

最佳答案 问答题库518位专家为你答疑解惑

很长一段时间,我的生活看似马上就要开始了。但是总有一些障碍阻挡着,有些事得先解决,有些工作还有待完成,时间貌似不够用,还有一笔债务8要去付清,然后生活就会开始。最后我终于明白,这些障碍,正是我的生活。 ——艾弗里德·德索萨

990. 等式方程的可满足性(一个比较经典的并查集例子)

class Solution {public boolean equationsPossible(String[] equations) {UF uf = new UF(26);for(String eq:equations){if(eq.charAt(1) == '='){char x = eq.charAt(0);char y = eq.charAt(3);uf.union(x-'a',y-'a');}}for(String eq:equations){if(eq.charAt(1) == '!'){char x = eq.charAt(0);char y = eq.charAt(3);if(uf.connocted(x-'a',y-'a')){return false;}}}return true;}  
}class UF{private int count;private int[] parent;public UF(int n){this.count = n;parent = new int[n];for(int i=0;i<n;i++){parent[i] = i;}}public void union(int p,int q){int rootP = find(p);int rootQ = find(q);if(rootP == rootQ) return;parent[rootP] = rootQ;count--;}public boolean connocted(int p,int q){int rootP = find(p);int rootQ = find(q);return rootP==rootQ;}public int find(int p){if(p!= parent[p]){parent[p] = find(parent[p]);}return parent[p];}public int count(){return count;}}

后续再补充真题

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"刷题笔记27——并查集":http://eshow365.cn/6-17648-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!