Ice_cream's world I

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

问题的意思是你可以吧这个分成几个封闭的图形,也就是几个环。如果一般的并查集,那么你肯定的输出结果是1,因为都是互相联通的,但是你需要找的是独立的空间,于是在你查找的需要每碰到一样的“祖宗”的话,就多分成一个独立的空间。

#include<stdio.h>

#include<string.h>

#include<algorithm>
using namespace std;
int n,m,a[1010],ans;
void cn()
{
    for(int i=0; i<n; i++)
        a[i]=i;
}
int find(int u)
{
    int v=u;
    while(a[v]!=v)
        v=a[v];
    int i=u,j;
    while(i!=v)
    {
        j=a[i];
        a[i]=v;
        i=j;
    }
    return v;
}
void cm(int x,int y)
{
    int tx=find(x);
    int ty=find(y);
    if(tx!=ty)
        a[tx]=ty;
    else
        ans++;
}
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        cn();
        int x,y;
        ans=0;
        for(int i=0; i<m; i++)
        {
            scanf("%d%d",&x,&y);
            cm(x,y);
        }
        printf("%d\n",ans);
    }
    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/aini875/article/details/81626570