http://acm.hdu.edu.cn/showproblem.php?pid=1213
并查集
#include<stdio.h> #include<iostream> #include<math.h> #include<stdlib.h> #include<ctype.h> #include<algorithm> #include<vector> #include<string.h> #include<queue> #include<stack> #include<set> #include<map> #include<sstream> #include<time.h> #include<utility> #include<malloc.h> #include<stdexcept> using namespace std; int n, m, t; int p[10000]; int b[10000]; int find(int x) { if (x == p[x]) return x; else return find(p[x]); } int fa, fb; void un(int x, int y) { fa = find(p[x]); fb = find(p[y]); if (fa != fb) { if (fa>fb) p[fa] = fb; else p[fb] = fa; } } int main() { scanf("%d",&t); while (t--) { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) p[i] = i; int sum = 0; int a, b; for (int i = 1; i <= m; i++) { scanf("%d%d", &a, &b); un(a, b); } for (int i = 1; i <= n; i++) { if (p[i] == i) sum++; } printf("%d\n", sum); } return 0; }
原文地址:http://blog.csdn.net/u014427196/article/details/42466617