标签:style blog color os io for ar 2014
很简单的一道题目,开始用的是并查集的分离集合森林做,不知道怎么的特别不稳定,太奇怪了,WA无数次,无奈之下改成一维数组了。。sad
AC
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <math.h> #define PI acos(-1,0) using namespace std; const int maxn = 30010; const int maxm = 100001; #define lson left, m, id<<1 #define rson m+1, right, id<<1|1 #define min(a,b) (a>b)?b:a #define max(a,b) (a>b)?a:b using namespace std; int father[50000]; int num[50000],n,m; int Find(int r) { int i = r,j; while(father[r]!=r) { r=father[r]; } while(father[i]!=r) { j = father[i]; father[i] = r; i = j; } return r; } void init() { for(int i = 0;i < n;i++) { father[i] = i; num[i] = 1; } } void Merge(int l,int b) { int y = Find(b); if(l != y) { father[y] = l; num[l] += num[y]; } } int main() { int j,k,l; while(~scanf("%d%d",&n,&m)) { if(n==0 && m==0) break; init(); int b; while(m--) { scanf("%d%d",&k,&l); int x = Find(l); for(j = 1;j < k;j++) { scanf("%d",&b); Merge(x,b); } } printf("%d\n",num[Find(0)]); } return 0; }
WA
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <math.h> #define PI acos(-1,0) using namespace std; const int maxn = 30010; const int maxm = 100001; #define lson left, m, id<<1 #define rson m+1, right, id<<1|1 #define min(a,b) (a>b)?b:a #define max(a,b) (a>b)?a:b using namespace std; struct node { int zhi , parent; } T[maxn]; int Find(int x) { return (x == T[x].parent) ? x : Find(T[x].parent); } void Merge(int x,int y) { int fx,fy; fx = Find(x); fy = Find(y); if(fx!=fy) { T[fy].parent = fx; T[fx].zhi += T[fy].zhi; } } int main() { int m,n,k; while (~scanf("%d%d",&n,&m)) { if (n==0 && m==0) break; for(int j = 0; j<n; j++) { T[j].zhi = 1; T[j].parent = j; } for(int i = 1; i <= m; ++i) { scanf("%d", &k); int *aa = new int[k]; for(int j = 0; j < k; ++j) { scanf("%d", &aa[j]); if(j != 0) Merge(aa[j - 1], aa[j]); } delete(aa); } printf("%d\n",T[T[0].parent].zhi); } return 0; }
answer 3
有时是正确结果,有时不是,特别无语啊。
3
POJ 1611 The Suspects(特别无语的并查集),布布扣,bubuko.com
POJ 1611 The Suspects(特别无语的并查集)
标签:style blog color os io for ar 2014
原文地址:http://blog.csdn.net/wjw0130/article/details/38589267