并查集

来源:互联网 发布:天猫销售数据 编辑:程序博客网 时间:2024/06/11 16:43

集合

判断两个点是不是在一个集合里面
检查图中有多少个孤立节点
很多问题都可以抽象为集合问题

代码

在合并两个树的同时,进行路径压缩。让所有的节点指向根节点。

#include <iostream>using namespace std;int Tree[1001];int N=1000;//寻找根节点int findRoot(int i){    if (Tree[i]==-1){        return i;    }    int root = findRoot(Tree[i]);    Tree[i] = root; //路径压缩    return root;}//合并两个集合void unite(int i,int j){    int root_i = findRoot(i);    int root_j = findRoot(j);    if (root_i!=root_j){        Tree[root_i] = root_j;        N--;    }}int main(){    int M;    while (cin>>N>>M&&N){        for (int i = 1; i <=1000 ; ++i) {            Tree[i]=-1;        }        for (int i = 0; i <M ; ++i) {            int x,y;            cin>>x>>y;            unite(x,y);        }        cout<<N-1<<endl;    }}

上面代码需要注意的地方:
Tree[root_i] = root_j;

0 0
原创粉丝点击