ALGORITHM1.5 Union-find implementation(p221)

时间:2022-09-05 16:41:53

//我在drjava里无法运行,所以没办法只能到终端里运行

//没有tinyUF.txt的请看我关于algs4环境配置的那片文章(里面有整本书测试数据的下载)

import edu.princeton.cs.algs4.*;

public class UF
{
    private int[] id;
    private int count;
    
    public UF(int N)
    {
        count = N;
        id = new int[N];
        for(int i = 0; i < N; i++)
        {
            id[i] = i;
        }
    }
    
    public int count()
    {
        return count;
    }
    
    public boolean connected(int p, int q)
    {
        return find(p) == find(q);
    }
    //我用了p222的quick-find
    public int find(int p)
    {
        return id[p];
    }
    
    public void union(int p, int q)
    {
        int pID = find(p);
        int qID = find(q);
        if(pID == qID)
            return;
        for(int i = 0; i < id.length; i++)
        {
            if(id[i] == pID)
                id[i] = qID;
        }
        count--;
    }
    
    public static void main(String[] args)
    {
        int N = StdIn.readInt();
        UF uf = new UF(N);
        while(!StdIn.isEmpty())
        {
            int p = StdIn.readInt();
            int q = StdIn.readInt();
            if(uf.connected(p,q))
                continue;
            uf.union(p,q);
            StdOut.println(p + " " + q);
        }
        StdOut.println(uf.count() + " components");
    }
}