A - the Ray ice table (disjoint-set)

Description

Ray has a special habit, usually like to collect all kinds of strange things, such as. . . . ,and also. . . . ,also include. . . . . Ray is a like share of the shoes, the Ray gave us a set of magical things, and that is unique in the world of ice coffee table! <o: p> </ o : p>
As the name suggests, the coffee table was frozen to live, the most important is that they are fragile, after all, it was frozen. So Ray to be very careful of moving them. Some table is frozen together, so that a table is divided into several parts ice and frozen if the table A and B together, B and C are frozen together, A and C will then frozen in, i.e. frozen state has passed sex, ABC at this time will be considered as a whole. <o: p> </ o : p>
To ensure the integrity of the ice coffee table, a block can only be moved Ray ice table, which is part of the frozen together. Ray wants to know all he needed to move several times to move the lab, can you help Xiaolei quickly calculate the answer to it?
Input

Plural sets of inputs, the first input group number T (1 <= T <= 200).
For each set of inputs, a first input integer n (1 <= n <= 100000), k (0 <= k <= 100000), table numbers 1 ~ n. <O: P>: </ P O>
K line after each line two numbers x, y (1 <= x , y <= n), represents the x-th and y-th table table frozen together.
Output

For each input, to output "Case z:" (without the quotes) represents a group, and then outputs an integer representing the number of Ray need to move.
Sample

Input

3
3 1
1 2
5 2
1 2
3 4
5 2
1 2
2 3
Output

. 1 Case: 2
Case 2:. 3
Case. 3:. 3
i.e. disjoint-set requirements with several groups

#include<stdlib.h>
#include<stdio.h>
#include<string.h>

int f[100010];
void init(int n)
{
    for(int i=1;i<=n;i++)
        f[i] = i;
}
int getf(int v)
{
    if(f[v] == v)
        return v;
    else
    {
        f[v] = getf(f[v]);
        return f[v];
    }
}
void Merge(int u,int v)
{
    int t1,t2;
    t1 = getf(u);
    t2 = getf(v);
    if(t1 != t2)
    {
        f[t2] = t1;
    }
}
int main()
{
    int t;
    int n,k;
    int u,v;
    scanf("%d",&t);
    for(int p=1;p<=t;p++)
    {
        int cnt = 0;
        scanf("%d %d",&n,&k);
        init(n);
        for(int i=0;i<k;i++)
        {
            scanf("%d %d",&u,&v);
            Merge(u,v);
        }
        for(int i=1;i<=n;i++)
        {
            if(f[i] == i)
                cnt++;
        }
        printf("Case %d: %d\n",p,cnt);
    }
    return 0;

}

Published 177 original articles · won praise 7 · views 30000 +

Guess you like

Origin blog.csdn.net/Fusheng_Yizhao/article/details/104905245