[数据结构]并查集

关于并查集的资料,可以查看维基百科关于并查集的定义

这里只是我实现并查集的一个记录

我更喜欢路径压缩,因为不需要使用额外的空间。

void makeSet(int* a, int n){

    for(int i = 0; i < n; ++i){

        a[i] = i;

    }

}

int find(int* a, int x){

    if(x == a[x]){

        return x;

    }

    else{

        return a[x] = find(a,a[x]);

    }

}

void unionSet(int* a,int x, int y){

    if(a[x] != a[y]){

        a[find(a,y)] = find(a,x);

    }

}

POJ上的关于并查集的练习,可以去感受一下并查集的魅力

http://poj.org/problem?id=1703

http://poj.org/problem?id=2421

http://poj.org/problem?id=2492

http://poj.org/problem?id=1861

http://poj.org/problem?id=1308

http://poj.org/problem?id=2524

参考文献

http://blog.csdn.net/jdplus/article/details/19494161

http://zh.wikipedia.org/wiki/%E5%B9%B6%E6%9F%A5%E9%9B%86


本文基于知识共享署名-非商业性使用 3.0 许可协议进行许可。欢迎转载、演绎,但是必须保留本文的署名林羽飞扬,若需咨询,请给我发信

你可能感兴趣的:(数据结构)