刷题笔记27——图论并查集

如果一个人,认为他的命运可以改变,那是因为老天让你这么认为的。 ——知乎天注定影评

class Solution {
    public boolean equationsPossible(String[] equations) {
        UF uf = new UF(26);
        for(String eq:equations){
            if(eq.charAt(1) == '='){
                char x = eq.charAt(0);
                char y = eq.charAt(3);
                uf.union(x-'a',y-'a');
            }
        }

        for(String eq:equations){
            if(eq.charAt(1) == '!'){
                char x = eq.charAt(0);
                char y = eq.charAt(3);
                if(uf.connocted(x-'a',y-'a')){
                    return false;
                }
            }
        }
        return true;
    }  
}

class UF{
    private int count;
    private int[] parent;

    public UF(int n){
        this.count = n;
        parent = new int[n];
        for(int i=0;i<n;i++){
            parent[i] = i;
        }
    }

    public void union(int p,int q){
        int rootP = find(p);
        int rootQ = find(q);

        if(rootP == rootQ) return;

        parent[rootP] = rootQ;
        count--;
    }

    public boolean connocted(int p,int q){
        int rootP = find(p);
        int rootQ = find(q);
        return rootP==rootQ;
    }

    public int find(int p){
        if(p!= parent[p]){
            parent[p] = find(parent[p]);
        }
        return parent[p];
    }

    public int count(){
        return count;
    }


}

你可能感兴趣的:(笔记,图论,java)