首页 > 其他分享 >【并查集】LeetCode 990. 等式方程的可满足性

【并查集】LeetCode 990. 等式方程的可满足性

时间:2023-02-28 21:11:34浏览次数:56  
标签:pre 990 int equation 查集 private find LeetCode charAt

题目链接

990. 等式方程的可满足性

思路

并查集模板题,模板可以参考 常用算法模板。将字母视为结点,== 表示有路径,!= 表示无路径。

  • 遍历 x == y,建立图前驱关系
  • 遍历 x != y,检查是否和前驱关系对应
  • 如果不对应,立即返回 false
  • 全部遍历完成说明没有问题,返回 true

代码

class Solution {
    private int[] pre = new int[26 + 3];

    public boolean equationsPossible(String[] equations) {
        init(26);

        // build graph
        for(String equation : equations){
            if(equation.charAt(1) == '!'){
                continue;
            }

            int indexFrom = equation.charAt(0) - 'a';
            int indexTo = equation.charAt(3) - 'a';
            mix(indexFrom, indexTo);
        }

        for(String equation : equations){
            if(equation.charAt(1) == '!'){
                int indexFrom = equation.charAt(0) - 'a';
                int indexTo = equation.charAt(3) - 'a';
                if(find(indexFrom) == find(indexTo)){
                    return false;
                }
            }
        }

        return true;
    }

    void init(int n) {
        for(int i = 0; i < n; i++){
            pre[i] = i;
        }
    }

    private void mix(int a, int b) {
        int fa = find(a);
        int fb = find(b);

        if(fa != fb){
            pre[fb] = fa;
        }
    }

    private int find(int x) {
        int r = x;
        while(r != pre[r]){
            r = pre[r];
        }
        merge(r, x);

        return r;
    }

    private void merge(int r, int x) {
        int i = x, j;
        while(pre[i] != r){
            j = pre[i];
            pre[i] = r;
            i = j;
        }
    }
}

标签:pre,990,int,equation,查集,private,find,LeetCode,charAt
From: https://www.cnblogs.com/shixuanliu/p/17165993.html

相关文章