POJ 1988 并查集 妙用deep数组

Cube Stacking
Time Limit: 2000MS   Memory Limit: 30000K
Total Submissions: 23635   Accepted: 8281
Case Time Limit: 1000MS

Description

Farmer John and Betsy are playing a game with N (1 <= N <= 30,000)identical cubes labeled 1 through N. They start with N stacks, each containing a single cube. Farmer John asks Betsy to perform P (1<= P <= 100,000) operation. There are two types of operations:
moves and counts.
* In a move operation, Farmer John asks Bessie to move the stack containing cube X on top of the stack containing cube Y.
* In a count operation, Farmer John asks Bessie to count the number of cubes on the stack with cube X that are under the cube X and report that value.

Write a program that can verify the results of the game.

Input

* Line 1: A single integer, P

* Lines 2..P+1: Each of these lines describes a legal operation. Line 2 describes the first operation, etc. Each line begins with a 'M' for a move operation or a 'C' for a count operation. For move operations, the line also contains two integers: X and Y.For count operations, the line also contains a single integer: X.

Note that the value for N does not appear in the input file. No move operation will request a move a stack onto itself.

Output

Print the output from each of the count operations in the same order as the input file.

Sample Input

6
M 1 6
C 1
M 2 4
M 2 6
C 3
C 4

Sample Output

1
0
2

题意:搬箱子和架箱子,如果箱子上面有箱子,则再不打乱顺序的条件下把整体搬过去

先普及下基础:并查集就是在路径压缩的条件下找根,每次在函数返回的时候,顺带把路上遇到的人的BOSS改为最后找到的祖宗编号。这样可以提高今后找到最高领导人(也就是树的祖先)的速度。然后再merge中判断是不是在一个连通分量,若不是,则连通,把一个连通图的根赋给另一个连通图,靠这样的方式去合并一个连通分量。

看了网上大牛的思路做出来的,在并查集的基础上加一个deep数组,用来存旧根的深度,旧根的深度等于新根上一次的节点数,这里就是一个线树,最后输出的时候,查根,减去改节点的深度,再减去本身,就得到下面的箱子,很巧妙啊,整体分为了根的节点数,本身,本身的深度三部分,思路实在巧妙。

如 给出这个数据:


#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
const int N =30010;
int father[N], jiedian[N], deep[N];

int find(int x)
{
	int temp;
	if(x == father[x])
		return x;
	temp = father[x];
	father[x] = find(temp);
	deep[x] += deep[temp]; //与根结点的距离
	return father[x];
}

int main()
{
    //freopen("in.txt","r",stdin);
	int p;
	char ope;
	int a, b;
	int query;
	int root1, root2;
	scanf("%d", &p);
	for(int i = 1; i < N; ++i) //init
	{
		father[i] = i;
		jiedian[i] = 1;
		deep[i] = 0;
	}
	for(int i = 0; i < p; ++i)
	{
		scanf("%*c%c", &ope);
		if(ope == 'M')
		{
			scanf("%d%d", &a, &b);
			root1 = find(a);
			root2 = find(b);
			if(root1 != root2)
			{
				father[root2] = root1;
				deep[root2] = jiedian[root1]; //更新深度,这里的深度指的是root2箱子上箱子的个数,因为root1架在上面,离根的距离
				jiedian[root1] += jiedian[root2]; //更新结点数,根下面的节点,包括根
			}
		}
		else
		{
			scanf("%d", &query);
			printf("%d\n", jiedian[find(query)] - deep[query] - 1); //减去自己
		}
	}
	return 0;
}


posted @ 2016-08-05 20:45  Lawliet__zmz  阅读(132)  评论(0编辑  收藏  举报