zoukankan      html  css  js  c++  java
  • Leetcode 990 等式方程的可满足性

    地址 https://leetcode-cn.com/problems/satisfiability-of-equality-equations/

    给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 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] 是 '='

    解答 

    很明显的 并查集模板

    先将相等的元素做一个并集,

    然后再搜索非相等的元素,在相等并集里搜索是否也有相同元素来判断是否成立

    class Solution {
    public:
    
        int euqal[26];
    
        void init(int n)
        {
            for (int i = 0; i < n; i++)
                euqal[i] = i;
        }    
    
        //代码实现
        int get(int x)
        {
            return x == euqal[x] ? x : euqal[x] = get(euqal[x]);
        }
    
        void merge(int x, int y)
        {
            euqal[get(x)] = get(y);
        }
    
        bool equationsPossible(vector<string>& equations) {
            init(26);
    
            for (int i = 0; i < equations.size(); i++) {
                string s = equations[i];
                string op = s.substr(1, 2);
                int a = s[0] - 'a';
                int b = s[3] - 'a';
    
                if (op == "==") {
                    merge(a, b);
                }
            }
    
            for (int i = 0; i < equations.size(); i++) {
                string s = equations[i];
                string op = s.substr(1, 2);
                int a = s[0] - 'a';
                int b = s[3] - 'a';
    
                if (op == "!=") {
                    if (get(a) == get(b))
                        return false;
                }
            }
    
            return true;
        }
        
    };
    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    C# 自定义泛型类,并添加约束
    WPF DataGrid 的RowDetailsTemplate的使用
    jquery腾讯微博
    WPF DataGrid的LoadingRow事件
    WPF DataGrid自定义列DataGridTextColumn.ElementStyle和DataGridTemplateColumn.CellTemplate
    WPF DataGrid支持的列类型
    WPF DataGrid自动生成列
    WPF DataTemplateSelector的使用
    WPF数据模板的数据触发器的使用
    UVa 1601 || POJ 3523 The Morning after Halloween (BFS || 双向BFS && 降维 && 状压)
  • 原文地址:https://www.cnblogs.com/itdef/p/13063860.html
Copyright © 2011-2022 走看看