zoukankan      html  css  js  c++  java
  • 990. Satisfiability of Equality Equations. 并查集

    Given an array equations of strings that represent relationships between variables, each string equations[i] has length 4 and takes one of two different forms: "a==b" or "a!=b".  Here, a and b are lowercase letters (not necessarily different) that represent one-letter variable names.

    Return true if and only if it is possible to assign integers to variable names so as to satisfy all the given equations.

    Example 1:

    Input: ["a==b","b!=a"]
    Output: false
    Explanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second. There is no way to assign the variables to satisfy both equations.
    Example 2:

    Input: ["ba","ab"]
    Output: true
    Explanation: We could assign a = 1 and b = 1 to satisfy both equations.
    Example 3:

    Input: ["ab","bc","a==c"]
    Output: true
    Example 4:

    Input: ["ab","b!=c","ca"]
    Output: false
    Example 5:

    Input: ["cc","bd","x!=z"]
    Output: true

    Note:

    1 <= equations.length <= 500
    equations[i].length == 4
    equations[i][0] and equations[i][3] are lowercase letters
    equations[i][1] is either '=' or '!'
    equations[i][2] is '='

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/satisfiability-of-equality-equations

    直接并查集

    class Solution {
    public:
        vector <int> fa;
    
        int find(int x){
            return x == fa[x] ? x : fa[x] = find(fa[x]);
        }
    
        void unite(int x,int y){
            int xx = find(x);
            int yy = find(y);
    
            fa[xx] = yy;
        }
    
        bool same(int x,int y){
            return find(x) == find(y);
        }
    
    
        bool equationsPossible(vector<string>& equations) {
            
            fa.resize(26);
            iota(fa.begin(), fa.end(), 0);
    
            for (auto str : equations){
                if (str[1] == '='){
                    int x = str[0] - 'a';
                    int y = str[3] - 'a';
                    unite(x,y);
                }
            }
    
            for (auto str : equations){
                if (str[1] == '!'){
                    int x = str[0] - 'a';
                    int y = str[3] - 'a';
                    if (same(x,y)){
                        return false;
                    }
                }
            }
    
            return true;
        }
    };
    
  • 相关阅读:
    掌握 ActionResult
    EF 的 霸气配置
    MVC 3 数据验证 Model Validation 详解
    Entity Framework 插入数据 解决主键非自增问题
    线程池(C#)
    socket 基础学习
    oracle创建job方法
    C# 任意类型数据转JSON格式
    JDBC(连接数据库的四个主要步骤)
    oracle 存储过程详细介绍(创建,删除存储过程,参数传递等)
  • 原文地址:https://www.cnblogs.com/xgbt/p/13068424.html
Copyright © 2011-2022 走看看