Quick-Union算法

前言:

    在上一节博客上已经介绍了Quick-Find算法,但是呢,Quick-Find算法太low了,运行慢,要是拿着它去找13亿人的关系链,那怕是电脑的风扇不太够用啊。所以我们这次学习它的升级版Quick-Union。

Quick-Union算法

回忆Quick-Find中union函数,就像是暴力强算,遍历所有数字的ID,然后把有着相同ID的数全部改掉,现在我们来引入“树”的概念来优化union函数,我们把每一个数的ID看做是连接它的枝,ID是谁就代表它的枝连向谁。比如说,ID[9] = 0,ID[0] = 5,ID[5] = 5,这就是一个数,即9->0->5,因为ID[5] 还是其本身,所以5就是树的根。union过程改为连接两个数的根,这样可以大大减少时间复杂度。

二话不说上代码,这里还是用的C++:

class quick_union{
private:
    //the count of connected components
    int count;
    
public:
    //initialize the ID_array
    void init_id(int *p_ID, int n){
        count = n;
        int i;
        for(i = 0; i< n; i++){
            p_ID[i] = i;
        }
        
    }
    
    //find the root of num
    int find(int *p_ID, int num){
        while(p_ID[num] != num)
        {
            num = p_ID[num];
        }
        return num;
    }
    
    //connect two components
    void union_id(int *p_ID, int x, int y){
        int root_x;
        int root_y;
        root_x = find(p_ID, x);
        root_y = find(p_ID, y);
        
        if(connected(p_ID, x, y) == false){
            p_ID[root_x] = root_y;
            count = count - 1;
        }
    }
    
    //judge if two components are connected
    bool connected(int *p_ID, int x, int y){
        if(find(p_ID, x) == find(p_ID, y)){
            return true;
        }
        else{
            return false;
        }
    }
    
    //cout the count of connected components
    void display(){
        cout << count << endl;
    }
    
};

来运行一下

#include <iostream>

using namespace std;

int main()
{
    int n, i;
    int *p_ID;
    quick_union f;
    
    cout << "Please enter the count of numbers: ";
    cin >> n;
    p_ID = new int [n];
    f.init_id(p_ID, n);
    for(i = 0; i < n; i++){
        cout << p_ID[i] << " ";
        
    }
    cout << endl;
    f.union_id(p_ID, 2 ,3);
    f.union_id(p_ID ,1, 0);
    f.union_id(p_ID, 0, 4);
    f.union_id(p_ID, 5, 7);
    
    for(i = 0; i < n; i++){
        cout << p_ID[i] << " ";
    }
    
    cout << endl;
    f.display();
    return 0;
}


结果

Please enter the count of numbers: 8

0 1 2 3 4 5 6 7 

4 0 3 3 4 7 6 7 

4


这样find的时间复杂度为O(logN~N),union的时间复杂度为O(1),为什么是logN呢?因为这是个树嘛,如果这个树连接的非常完美(二叉树),就是每一个节点都伸出去两条枝,这样的情况下假如有N个结点的树,需要logN步就可以可以找到根。但如果这棵树很极端,就是一颗光杆司令(每一个结点伸出一条枝),那么就需要N步才能找到根。

综合一下,如果是共有N个数,要连接其中M个,则最后时间复杂度为O(M*(logN~N))。

总结:

这种算法find较慢,union很快,所以称为Quick-Union,这种算法已经比Quick-FInd快了许多,不要小看LogN与N的区别,就拿2048个数来比较,运行2048次和11次能一样吗?

接下来还会继续优化这一算法,也就是最终豪华版Union-Find。


最后强烈推荐Coursera上普林斯顿大学的算法课点击打开链接


以上内容纯属个人学习总结,不代表任何团体或单位。若有理解不到之处请见谅!



猜你喜欢

转载自blog.csdn.net/qq_39747794/article/details/80254661