【HDOJ】3560 Graph’s Cycle Component

时间:2023-03-08 16:37:10
【HDOJ】3560 Graph’s Cycle Component

并查集的路径压缩。

 #include <stdio.h>
#include <string.h> #define MAXNUM 100005 int deg[MAXNUM], bin[MAXNUM];
char isCycle[MAXNUM]; 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;
int fy; fx = find(x);
fy = find(y);
if (fx != fy)
bin[fx] = fy;
} int main() {
int n, m;
int i, x, y; while (scanf("%d %d", &n, &m)!=EOF && (n||m)) {
for (i=; i<n; ++i)
bin[i] = i;
memset(isCycle, , sizeof(isCycle));
memset(deg, , sizeof(deg));
while (m--) {
scanf("%d %d", &x, &y);
deg[x]++;
deg[y]++;
merge(x, y);
}
m = ;
for (i=; i<n; ++i) {
x = find(i);
if (isCycle[x] == ) {
++m;
isCycle[x] = ;
}
}
for (i=; i<n; ++i)
if (deg[i] != )
isCycle[bin[i]] = ;
x = ;
for (i=; i<n; ++i)
if (isCycle[i])
++x;
printf("%d %d\n", m, x);
} return ;
}