标签:style blog io for sp on 2014 log amp
并查集的模板题,为了避免麻烦,合并的时候根节点大的合并到小的结点。
#include<cstdio> #include<algorithm> using namespace std; const int maxn = 33333; int fa[maxn]; int num[maxn]; int n,m,t; void init(){ for(int i = 0; i < n; i++) {fa[i] = i; num[i] = 1;} } int find_father(int u){ return fa[u] == u ? u : fa[u] = find_father(fa[u]); } int main(){ while(scanf("%d%d",&n,&m)){ if(!m && !n) break; init(); for(int i = 0; i < m; i++){ scanf("%d",&t); int x,y; for(int j = 0; j < t; j++){ scanf("%d",&y); if(!j) x = y; else{ int fy = find_father(y); int fx = find_father(x); if(fy > fx) swap(fy,fx); //为了避免麻烦,统一让小的根合并到大的根 if(fy != fx){ fa[fy] = fx; num[fx] += num[fy]; } } } } t = find_father(0); printf("%d\n",num[t]); } return 0; }
标签:style blog io for sp on 2014 log amp
原文地址:http://blog.csdn.net/u013451221/article/details/40623771