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;
        }
    };
    
  • 相关阅读:
    数据库的创建与管理
    html+css画虚线,实线
    隐藏导航练习
    表单—注册邮箱
    整理—运算符l
    softmax函数理解
    离线配置Anaconda3+tensorflow-gpu1.4.0+cuda8.0+cudnn6.0
    stl总结精简版
    hdu_2030
    康托展开
  • 原文地址:https://www.cnblogs.com/xgbt/p/13068424.html
Copyright © 2011-2022 走看看