算法练习(94): UF实现(1.5.7)

本系列博客习题来自《算法(第四版)》,算是本人的读书笔记,如果有人在读这本书的,欢迎大家多多交流。为了方便讨论,本人新建了一个微信群(算法交流),想要加入的,请添加我的微信号:zhujinhui207407 谢谢。另外,本人的个人博客 http://www.kyson.cn 也在不停的更新中,欢迎一起讨论

算法练习(94): UF实现(1.5.7)_第1张图片
算法(第4版)

知识点

  • QuickUnionUF
  • QuickFindUF

题目

1.5.7 分别为 quick-find 算法和 quick-union 算法实现 QuickFindUF 类和 QuickUnionUF 类。


1.5.7 Develop classes QuickUnionUF and QuickFindUF that implement quick-union and quick-find, respectively.

分析

这个之前在
算法练习(90):quick-find(1.5.1)
算法练习(91):quick-union(1.5.2)
已经实现过

答案

public class QuickFindUF {
    private int[] id;     // access to component id (site indexed)
    private int count;    // number of components

    public QuickFindUF(int N){
        id = new int[N];
        for (int i = 0; i < N; i++) {
            id[i] = i;
        }
    }

    public int find(int p) {
        return id[p];
    }

    public void union(int p, int q) {  // Put p and q into the same component.
        int pID = find(p);
        int qID = find(q);
        // Nothing to do if p and q are already in the same component.
        if (pID == qID) return;
        // Rename p’s component to q’s name.
        for (int i = 0; i < id.length; i++)
            if (id[i] == pID) id[i] = qID;
        count--;
    }
}
public class QuickUnionUF {
    private int[] id;     // access to component id (site indexed)
    private int count;    // number of components

    public QuickUnionUF(int N){
        id = new int[N];
        for (int i = 0; i < N; i++) {
            id[i] = i;
        }
    }

    private int find(int p)
    {
        // Find component name.
        while (p != id[p]) p = id[p];
        return p;
    }
    public void union(int p, int q)
    {  // Give p and q the same root.
        int pRoot = find(p);
        int qRoot = find(q);
        if (pRoot == qRoot) return;
        id[pRoot] = qRoot;
        count--;
    }
}

你可能感兴趣的:(算法练习(94): UF实现(1.5.7))