hdu2120 并查集

并查集的作用:

1.求联通分量的个数

2.判断图中是否有环



ice_cream's world is a rich country, it has many fertile lands. Today, the queen of ice_cream wants award land to diligent ACMers. So there are some watchtowers are set up, and wall between watchtowers be build, in order to partition the ice_cream’s world. But how many ACMers at most can be awarded by the queen is a big problem. One wall-surrounded land must be given to only one ACMer and no walls are crossed, if you can help the queen solve this problem, you will be get a land.

Input
In the case, first two integers N, M (N<=1000, M<=10000) is represent the number of watchtower and the number of wall. The watchtower numbered from 0 to N-1. Next following M lines, every line contain two integers A, B mean between A and B has a wall(A and B are distinct). Terminate by end of file.

Output
Output the maximum number of ACMers who will be awarded.
One answer one line.

Sample Input
   
   
   
   
8 10 0 1 1 2 1 3 2 4 3 4 0 5 5 6 6 7 3 6 4 7

Sample Output

3



把对应的灯塔看作顶点,把之间的围墙看作无向边,当整个图存在环的时候,形成一个地方。

#include<iostream>
using namespace std;
int pre[1005];//pre[x]=y;树中x的前驱节点为y
int findset(int x)//x属于那个集合,即求x的根结点
{
    if(pre[x]!=x)
        return pre[x]=findset(pre[x]);
    else
        return x;
}
int union_set(int a,int b)//合并集合x,y
{
    int x=findset(a);
    int y=findset(b);
    if(x==y)
        return 1;
    else
    {
        pre[x]=y;//顺序无所谓,2棵树合并为1棵,1棵树的根节点指向另一颗的根节点
        return 0;
    }
}
int main()
{
    int n,m;
    while(cin>>n>>m)
    {
    for(int i=0;i<=n-1;i++)
        pre[i]=i;
    int sum=0;
    for(int i=1;i<=m;i++)
    {
        int a,b;
        cin>>a>>b;
        sum+=union_set(a,b);
    }
    cout<<sum<<endl;
    }
    return 0;
}

并查集模板
int findset(int x)//x属于那个集合,即求x的根结点
{
    if(pre[x]!=x)
        return pre[x]=findset(pre[x]);
    else
        return x;
}

void union_set(int a,int b)//合并集合x,y
{
    int x=findset(a);
    int y=findset(b);
    if(x==y)//x和y在同一个集合,会形成环
        return ;
    pre[x]=y;//顺序无所谓,2棵树合并为1棵,1棵树的根节点指向另一颗的根节点
}


你可能感兴趣的:(并查集)