#include <cstdlib> #include <iostream> #include <cstdio> using namespace std; const int MAX = 30001; int parent[MAX]; int num[MAX]; void initUnion(int count) { for(int i=0; i<count; i++) { parent[i] = i; num[i] = 1; } } int findElem(int elem) { if(parent[elem] != elem) parent[elem] = findElem(parent[elem]); return parent[elem]; } void unionElem(int a, int b) { int x = findElem(a); int y = findElem(b); if(x == y) return; if(num[x] <= num[y]) { parent[x] = y; num[y] += num[x]; } else { parent[y] = x; num[<mce:script type="text/javascript" src="http://hi.images.csdn.net/js/blog/tiny_mce/themes/advanced/langs/zh.js" mce_src="http://hi.images.csdn.net/js/blog/tiny_mce/themes/advanced/langs/zh.js"></mce:script><mce:script type="text/javascript" src="http://hi.images.csdn.net/js/blog/tiny_mce/plugins/syntaxhl/langs/zh.js" mce_src="http://hi.images.csdn.net/js/blog/tiny_mce/plugins/syntaxhl/langs/zh.js"></mce:script>x] += num[y]; } } int main(int argc, char *argv[]) { int m, n; //freopen("input.txt", "rt", stdin); //freopen("output.txt", "wt", stdout); while(scanf("%d%d", &n, &m) && n != 0) { initUnion(n); while(m-- > 0) { int eachGroup; scanf("%d", &eachGroup); int first, other; scanf("%d", &first); while(eachGroup-- > 1) { scanf("%d", &other); unionElem(first, other); } } printf("%d/n", num[findElem(0)]); } return EXIT_SUCCESS; } 初次使用并查集...