1. 程式人生 > >POJ1988 Cube Stacking【帶權並查集 統計】

POJ1988 Cube Stacking【帶權並查集 統計】

Cube Stacking

Time Limit: 2000MS   Memory Limit: 30000K
Total Submissions: 28711   Accepted: 10081
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

Source

USACO 2004 U S Open

問題連結:POJ1988 Cube Stacking

問題描述:有n個相同的立方體(從1開始編號),開始有n堆(每堆一個),有P次操作,每次有兩種選擇,操作一M X Y,將包含立方體X的一堆移動包含立方體Y的一堆的上面,操作二C X,查詢立方體X下面的立方體的個數。對於每個查詢操作,輸出相應的答案。

解題思路:帶權並查集,讓每堆中各個立方體都以最頂上的立方體為祖先結點,設結點 i 的祖先結點為 j ,cnt[i] 表示結點 i 到 j之間的立方體數,sum[j]表示以結點 j 為祖先結點的立方體數,則C i 的結果為 sum[j] - cnt[i]

AC的C++程式碼:

#include<iostream>

using namespace std;

const int N=30010;
int pre[N],cnt[N],sum[N];//pre儲存結點i的父節點,cnt儲存結點i到父結點之間的立方體數,sum儲存以結點i為祖先結點的立方體數

void init()
{
	for(int i=0;i<N;i++){
		pre[i]=i;//初始化每個結點的父結點為自己 
		cnt[i]=0;//自己到自己之間只有0個 
		sum[i]=1;//本身只有一個 
	}
} 

int find(int x)
{
	if(x!=pre[x]){
		int r=pre[x];
		pre[x]=find(r);
		cnt[x]+=cnt[r];//原來x的父結點為r,x到r之間的立方體數為cnt[x]。現在x的父結點為pre[x],x到pre[x]之間的立方體數為cnt[i]+=cnt[r] 
	}
	return pre[x];
}

//將x這一堆移動到y這一堆的頂上 
void join(int x,int y)
{
	int fx=find(x);//x一堆的頂上立方體為fx 
	int fy=find(y);//y一堆的頂上立方體為fy 
	if(fx!=fy){
		pre[fy]=fx;//由於是x這一堆移動到y這一堆上,因此fy的父節點為fx 
		cnt[fy]=sum[fx];//fy到父節點fx之間的立方體數=原來x這一堆的立方體數 (即sum[fx]) 
		sum[fx]+=sum[fy];//如今以fx為根結點的立方體數是兩堆立方體數之和 
	}
}

int main()
{
	int p;
	init();
	scanf("%d",&p);
	while(p--){
		char c;
		int x,y;
		scanf(" %c",&c);
		if(c=='M'){
			scanf("%d%d",&x,&y);
			join(x,y);
		}
		else if(c=='C'){
			scanf("%d",&x);
			int r=find(x);
			printf("%d\n",sum[r]-cnt[x]-1);
		}	
	}
	return 0;
}