Leetcode 990. 等式方程的可满足性(中等) 并查集
题目:
给你一个数组 equations
,装着若干字符串表示的算式。每个算式 equations[i]
长度都是 4,而且只有这两种情况:a==b
或者 a!=b
,其中 a,b
可以是任意小写字母。你写一个算法,如果 equations
中所有算式都不会互相冲突,返回 true,否则返回 false。
比如说,输入 ["a==b","b!=c","c==a"]
,算法返回 false,因为这三个算式不可能同时正确。
再比如,输入 ["c==c","b==d","x!=z"]
,算法返回 true,因为这三个算式并不会造成逻辑冲突。
思路:
先使用a==b这些构建并查集,然后对不等式进行并查集查询。当结果不同时证明冲突
class UF { public: UF(int n){ count=n; for(int i=0;i<n;++i){ parent.push_back(i); size.push_back(1); } } void Union(int p, int q){ int rootp=find(p); int rootq=find(q); if(rootp==rootq){ return; } if(size[rootp]>size[rootq]){ size[rootq]+=size[rootp]; parent[rootp]=rootq; }else{ size[rootp]+=size[rootq]; parent[rootq]=rootp; } count--; } int find(int x){ while(x!=parent[x]){ parent[x]=parent[parent[x]]; x=parent[x]; } return x; } bool connected(int p,int q){ int rootp=find(p); int rootq=find(q); return rootp==rootq; } int count; vector<int> parent; vector<int> size; }; class Solution { public: bool equationsPossible(vector<string>& equations) { int n=equations.size(); UF uf(26); bool ok=true; for(int i=0;i<n;++i){ int p=equations[i][0]-'a'; int q=equations[i][3]-'a'; bool eq=equations[i][1]=='='; if(eq){ uf.Union(p,q); } } for(int i=0;i<n;++i){ int p=equations[i][0]-'a'; int q=equations[i][3]-'a'; bool eq=equations[i][1]=='='; if(!eq){ if(uf.connected(p,q)){ ok=false; } } } return ok; } };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
2016-02-22 Handler 消息传递机制
2016-02-22 android 中退出程序的两种方式
2016-02-22 10 个迅速提升你 Git 水平的提示