[Princeton Algorithms I] Union-Find

本文详细介绍了动态连通性问题及其解决数据结构——Union-Find。内容涵盖Quick-Find、Quick-Union、Weighted Quick-Union以及Weighted Quick-Union with Path Compression(WQUPC)的实现和成本模型。Quick-Find虽然简单但效率低下,而Quick-Union通过延迟连接更新避免了高成本,但可能导致树形结构失衡。Weighted Quick-Union通过将较小的树连接到较大的树来平衡结构,进一步优化了查找时间。WQUPC通过路径压缩进一步提高性能,使得查找和合并操作的时间复杂度接近O(log n)。此外,还探讨了Union-Find在如渗透问题等应用中的重要性。
摘要由CSDN通过智能技术生成

Union-Find

https://algs4.cs.princeton.edu/15uf/

Dynamic Connectivity Problem

a dynamic connectivity structure is a data structure that dynamically maintains information about the connected components of a graph.

Union-Find API

在这里插入图片描述

Implementations

Quick-Find (eager approach)

在这里插入图片描述
Data Structure:

  • Integer array id[ ] of size N
  • Interpretation: p and q are connected iff they have the same id
  • default config: each id equals to its index

Find: check if p and q have the same id

Union: To merge components contatining p and q, change all entires whose id equals id[p] to id[q]

Implementation
public class QuickFindUF {
   
    private int[] id;    // id[i] = component identifier of i
    private int count;   // number of components

    /**
    constructor
     */
    public QuickFindUF(int n) {
   
        count = n;
        id = new int[n];
        for (int i = 0; i < n; i++)
            id[i] = i;
    }
  
    /**
     * Returns the number of sets.
     */
    public int count() {
   
        return count;
    }
  
    /**
     * Returns the canonical element of the set containing element p.
     */
    public int find(int p) {
   
        validate(p);
        return id[p];
    }

    // validate that p is a valid index
    private void validate(int p) {
   
        int n = id.length;
        if (p < 0 || p >= n) {
   
            throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n-1));
        }
    }

    /**
     * Returns true if the two elements are in the same set.
     */
    @Deprecated
    public boolean connected(int p, int q) {
   
        validate(p);
        validate(q);
        return id[p] == id[q
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值