[1][Algorithm] Union-Find 并查集

Outline

  • dynamic connectivity
  • quick find
  • quick union
  • implementations
  • applications

Dynamic connectivity

  1. Union command
  2. Find/connected query(yes/no)
  • connected component

Quick Find[eager approach]

public class QuickFindUF {
    private int[] id;
    
    // O(N)
    public QuickFindUF(int x) {
        id = new int[N];
        for (int i=0; i

Quick Union[lazy approach]


public class QuickUnion {
    // id[i] represents the root of i
    private int[] id;

    // O(N)
    public QuickUnion(int N) {
        id = new int[N];
        for (int i=0; i

Improvements

WeightedQU

    private int[] sz;

    // O(lgN)
    public Union(int p, int q) {
        int rootp = root(p);
        int rootq = root(q);
        if (sz[rootp] >= sz[rootq]) {
            id[rootq] = rootp;
            sz[rootp] += sz[rootq];
        } else {
            id[rootp] = rootq;
            sz[rootq] += sz[rootp];
        }        
    }

Path Compression

    // O(lgN)
    private int root(int x) {
        while (id[x] != x) {
            id[x] = id[id[x]];
            x = id[x];
        }
        return x;
    }

Cost

algorithm initialization union find
Quick Find N N 1
Quick Union(worst case) N N N
WeightedQU(worst case) N lgN lgN
  • Quick Find
  1. Union too expensive.
  2. Trees can be too fat.
  • Quick Union
  1. Find too expensive.
  2. Trees can be too tall.

你可能感兴趣的:([1][Algorithm] Union-Find 并查集)