【HDOJ】2473 Junk-Mail Filter

时间:2022-12-25 10:55:43

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

 #include <stdio.h>
#include <string.h> #define MAXNUM 1000050 int bin[MAXNUM], assist[MAXNUM];
char visit[MAXNUM];
int n, ext; int find(int x) {
int r = x;
int i = x, j; while (r != bin[r])
r = bin[r]; while (i != r) {
j = bin[i];
bin[i] = r;
i = j;
} return r;
} void merge(int x, int y) {
int fx, fy; fx = find(x);
fy = find(y); if (fx != fy) {
bin[fx] = fy;
}
} void extract(int x) {
bin[ext] = ext;
assist[x] = ext++;
} int main() {
int m, t=;
int i, x, y;
char ch; while (scanf("%d %d", &n, &m)!=EOF && (n||m)) {
memset(bin, , sizeof(bin));
memset(assist, , sizeof(assist));
memset(visit, , sizeof(visit));
for (i=; i<n; ++i) {
bin[i] = i;
assist[i] = i;
}
ext = n;
while (m--) {
scanf("%*c%c", &ch);
if (ch == 'M') {
scanf("%d %d", &x, &y);
x = assist[x];
y = assist[y];
merge(x, y);
} else {
scanf("%d", &x);
extract(x);
}
}
m = ;
for (i=; i<n; ++i) {
x = find(assist[i]);
if (visit[x] == ) {
++m;
visit[x] = ;
}
}
printf("Case #%d: %d\n", t++, m);
} return ;
}