【HDOJ】2473 Junk-Mail Filter

并查集删除结点,方法是构建虚拟点,做映射。

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 #define MAXNUM 1000050
 5 
 6 int bin[MAXNUM], assist[MAXNUM];
 7 char visit[MAXNUM];
 8 int n, ext;
 9 
10 int find(int x) {
11     int r = x;
12     int i = x, j;
13 
14     while (r != bin[r])
15         r = bin[r];
16 
17     while (i != r) {
18         j = bin[i];
19         bin[i] = r;
20         i = j;
21     }
22 
23     return r;
24 }
25 
26 void merge(int x, int y) {
27     int fx, fy;
28 
29     fx = find(x);
30     fy = find(y);
31 
32     if (fx != fy) {
33         bin[fx] = fy;
34     }
35 }
36 
37 void extract(int x) {
38     bin[ext] = ext;
39     assist[x] = ext++;
40 }
41 
42 int main() {
43     int m, t=1;
44     int i, x, y;
45     char ch;
46 
47     while (scanf("%d %d", &n, &m)!=EOF && (n||m)) {
48         memset(bin, 0, sizeof(bin));
49         memset(assist, 0, sizeof(assist));
50         memset(visit, 0, sizeof(visit));
51         for (i=0; i<n; ++i) {
52             bin[i] = i;
53             assist[i] = i;
54         }
55         ext = n;
56         while (m--) {
57             scanf("%*c%c", &ch);
58             if (ch == 'M') {
59                 scanf("%d %d", &x, &y);
60                 x = assist[x];
61                 y = assist[y];
62                 merge(x, y);
63             } else {
64                 scanf("%d", &x);
65                 extract(x);
66             }
67         }
68         m = 0;
69         for (i=0; i<n; ++i) {
70             x = find(assist[i]);
71             if (visit[x] == 0) {
72                 ++m;
73                 visit[x] = 1;
74             }
75         }
76         printf("Case #%d: %d\n", t++, m);
77     }
78 
79     return 0;
80 }

 

posted on 2014-04-29 17:02  Bombe  阅读(141)  评论(0编辑  收藏  举报

导航