美文网首页
算法练习(94): UF实现(1.5.7)

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

作者: kyson老师 | 来源:发表于2018-01-14 23:21 被阅读86次

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

算法(第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)

    本系列博客习题来自《算法(第四版)》,算是本人的读书笔记,如果有人在读这本书的,欢迎大家多多交流。为了方便讨论,本...

  • 1.5.7

    青岛四日游 第一次坐轮船 农贸市场的海鲜真是不错,买来加工,吃到饱饱这几天会说不少字,会叫爷爷,站在东西上喊“高...

  • 编程作业(七)

    K均值算法与主成分分析算法 K均值分析算法 在本部分练习中,你将实现K均值算法并将该算法用于图像压缩。最初,你通过...

  • npm install 固定某个版本

    npm install --savereact-navigation@1.5.7

  • UF问题

    温习以下解决方体的思路:分析问题并找到解决问题的方案,将解决方案分成多个api。则要解决的问题就变成了实现api。...

  • 练习94

  • 练习(94)

    坏消息还不如没有消息!

  • LeetCode(1. 两数之和)

    算法描述 : 算法实现 : Java实现 : Python实现

  • 小白硬件常识——电阻选型从哪几方面考虑?

    一般从以下几个方面进行考虑: 容值:电容值;(0.1uf、10uf、100uf,可以通过电容并联提高容值) 电容类...

  • LeetCode(9. 回文数)

    算法描述 : 算法实现 : Java实现 :

网友评论

      本文标题:算法练习(94): UF实现(1.5.7)

      本文链接:https://www.haomeiwen.com/subject/wrnloxtx.html