HDU 1213

#include<stdio.h>
int father[1005],depth[1005];
void init()
{
    int i;
    for(i = 1; i < 1005;i ++)
    {
        father[i] = i;
        depth[i] = 0;
    }
}

int find(int x)
{
    if(x==father[x])
        return x;
    else
        return father[x] = find(father[x]);
}

void unit(int x,int y)
{
    x = find(x);
    y = find(y);
    if(x==y)
        return ;
    if(depth[x]<depth[y])
    {
        father[x] = father[y];

    }
    else
    {
        if(depth[x]>depth[y])
            father[y] = father[x];
        else
        {
            father[x] = father[y];
            depth[y]++;
        }
    }
}

int main()
{
    int T,n,m,gr,j,a,b;
    scanf("%d",&T);
    while(T--)
    {
        gr = 0;
        init();
        scanf("%d%d",&n,&m);
        while(m--)
        {
            scanf("%d%d",&a,&b);
            unit(a,b);
        }
        for(j = 1;j <= n;j ++)
        {
            if(j == father[j])
                gr++;
        }
        printf("%d\n",gr);
    }
    return 0;
}


posted on 2014-04-30 18:34  wangzhili  阅读(82)  评论(0编辑  收藏  举报