并查集练习
hdu1232
#define _CRT_SECURE_NO_DEPRECATE #include<stdio.h> #define MAX 1100 int par[MAX], n; int find(int x){ if (par[x] == x){ return x; } return par[x] = find(par[x]); } void united(int x, int y){ int a = find(x), b = find(y); if (a != b){ par[a] = b; } } int main() { int m, a, b, i, res; while (scanf("%d", &n)!=-1, n){ scanf("%d", &m); for (i = 1; i <= n; i++)par[i] = i; for (i = 0; i < m; i++){ scanf("%d %d", &a, &b); united(a, b); } res = 0; for (i = 1; i <= n; i++){ if (par[i] == i){ res = res + 1; } } printf("%d\n", res - 1); } return 0; }
世上无难事,只要肯登攀。