本文出自:http://blog.csdn.net/svitter
开始有N堆方块,编号从1~n。每次移动一堆方块,最后求某个方块下面方块的个数。
开始输入一个数字P,代表输入操作个数。
此处发现在g++4.8的版本中,类似与 char ch[0]这样的数组也是可以开辟的。。。
一个不小心开辟了这样一个数组。。然后return 0完全找不到错误所在。。
随后的2~1+p行,每行一组操作数据。
M i j代表移动i的堆到j的堆上。
C i代表求出i以下的方块个数。
#include <iostream> #include <stdio.h> #include <string.h> using namespace std; const int MAXN = 30010; int root[MAXN]; int under[MAXN]; int sum[MAXN]; void init() { for(int i = 0; i < MAXN; i++) { root[i] = i; under[i] = 0; sum[i] = 1; } } int getRoot(int i) { if(i == root[i]) return i; int t = getRoot(root[i]); under[i] += under[root[i]]; root[i] = t; return root[i]; } int a,b; void Merge(int i, int j) { a = getRoot(i); b = getRoot(j); if(a == b) return; root[a] = b; under[a] = sum[b]; sum[b] += sum[a]; } int main() { int p; char ch[0]; int t1, t2; init(); scanf("%d", &p); while(p--) { scanf("%s", ch); if(ch[0] == 'M') { scanf("%d", &t1); scanf("%d", &t2); Merge(t1, t2); } else { scanf("%d", &t1); getRoot(t1); printf("%d\n", under[t1]); } } return 0; }
POJ1988 CubeStacking (并查集),布布扣,bubuko.com
原文:http://blog.csdn.net/svitter/article/details/38311937