水题,并查集简单应用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N 50005
int uf_set[N];
int sum;

void Init()
{
    memset(uf_set, -1, sizeof(uf_set));
}

int Find(int x)
{
    if (uf_set[x] < 0)
        return x;
    else {
        uf_set[x] = Find(uf_set[x]);
        return uf_set[x];
    }
}

void Union(int r1, int r2)
{
    int a = Find(r1);
    int b = Find(r2);
    if (a == b)
        return;
    if (uf_set[a] < uf_set[b]) {
        uf_set[a] += uf_set[b];
        uf_set[b] = a;
    } else {
        uf_set[b] += uf_set[a];
        uf_set[a] = b;
    }
    --sum;
}

int main(int argc, char *argv[])
{
    int c = 1, n, m;
    while (1) {
        scanf("%d%d", &n, &m);
        if (n == 0)
            break;
        sum = n;
        Init();
        while (m--) {
            int x, y;
            scanf("%d%d", &x, &y);
            Union(x, y);
        }
        printf("Case %d: %d\n", c++, sum);
    }
    return 0;
}