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] 是 '='

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/satisfiability-of-equality-equations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

基本思路:使用并查集,先用等式关系建立并查集,再用不等式校验,可参考我之前的并查集总结

    vector<char>  parent,psize;
    int find(int x){
        if(x!=parent[x])
            parent[x]=find(parent[x]);
        return parent[x];
    }
    
    void UN(int x,int y){
        int rootp=find(x);
        int rootq=find(y);
        if(rootq!=rootp){
            if(psize[rootp]<psize[rootq]){
                parent[rootp]=rootq;
                psize[rootq]+=psize[rootp];
            }
            else{
                parent[rootq]=rootp;
                psize[rootp]+=psize[rootq];
            }
        }
    }
    bool connect(int x,int y){
        int rootp=find(x);
        int rootq=find(y);
        return rootp==rootq;
    }
    bool equationsPossible(vector<string>& equations) {
        parent.resize(26,0);
        psize.resize(26,1);
        for(int i=0;i<26;i++){
            parent[i]=i;
        }
        
        stack<pair<int,int>> unequation;
        for(int i=0;i<equations.size();i++){
            int a=equations[i][0]-'a';
            int b=equations[i][3]-'a';
            char op=equations[i][1];
            if(op=='='){
                UN(a,b);
            }
            else{
                unequation.push({a,b});
            }
        }
        while(!unequation.empty()){
            int a=unequation.top().first;
            int b=unequation.top().second;
            unequation.pop();
            if(connect(a,b))
                return false;
        }
        return true;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值