poj 1988 Cube Stacking(带权并查集)

题目:poj 1988 Cube Stacking(带权并查集)


题目大意:给出n个方块,然后执行操作, M x y 就是将这个x那一堆 移到 y的上方。然后c X 就是问x下方有对少方块。


解题思路:根节点记录下它的下方有多少个方块,然后这个集合里的每个方块都有权值,代表这个方块距离根之间有多少的方块。这样查讯到这个节点的时候就只要将根节点的个数减去权值 就得到答案 ( + 1 或不加1 看权值如何给定)。


代码:

#include <stdio.h>

const int N = 30005;

int p, f[N], c[N], num[N];

void init () {

	for (int i = 0; i < N; i++) {

		f[i] = i;
		c[i] = 0;
		num[i] = 1;
	}
}

int getfather (int x) {

	if ( x != f[x]) {

		int t = f[x];
		f[x] = getfather (f[x]);
		c[x] =  c[x] + c[t];

	}
	return f[x];
}

void unions (int p , int q) {

	f[p] = q;
	c[p] = num[q];
	num[q] += num[p];

}

int main () {
	
	scanf ("%d", &p);
	char s[10];
	int x, y;
	init ();
	while (p--) {

		scanf ("%s", s);
		if (s[0] == 'M') {

			scanf ("%d%d", &x, &y);
			int q = getfather (x);
			int p = getfather (y);
//			printf ("%d %d\n", q, p);
			if (p != q) 
				unions (p, q);

		} else {

			scanf ("%d", &x);
			int q = getfather (x);
//			printf ("%d %d\n", num[q], c[x]);
			printf ("%d\n", num[q] - c[x] - 1);
		}
	}
	return 0;
}


你可能感兴趣的:(poj 1988 Cube Stacking(带权并查集))