Cube Stacking(并差集深度+结点个数)

时间:2023-03-10 04:51:18
Cube Stacking(并差集深度+结点个数)
Cube Stacking
Time Limit: 2000MS   Memory Limit: 30000K
Total Submissions: 21567   Accepted: 7554
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
题意:有n个从1到n编号的箱子,将每个箱子当做一个栈,对这些箱子进行p次操作,每次操作分别为以下两种之一:
           1>输入 M x y:表示将编号为x的箱子所在的栈放在编号为y的箱子所在栈的栈顶.
           2>输入 C x:计算编号为x的所表示的栈中在x号箱子下面的箱子数目.
题解:和龙珠那题一样,坑了半天,写的都醉了。。。
ac代码贴上:
 #include<stdio.h>
#include<string.h>
const int MAXN=;
int pre[MAXN],s[MAXN],dep[MAXN];//s数组存当前树的节点数;
int find(int x){
if(x!=pre[x]){
int t=pre[x];
pre[x]=find(pre[x]);
dep[x]+=dep[t];
}
/* int i=x,j;
while(i!=r){
j=pre[i];pre[i]=r;i=j;
}*/
return pre[x];
}
void merge(int x,int y){
int f1,f2;
f1=find(x);f2=find(y);
// printf("%d %d\n",f1,f2);
if(f1!=f2){
pre[f2]=f1;
dep[f2]=s[f1];
s[f1]+=s[f2];
}
}
int main(){
int N,x,y;
char c[];//定义成s了,错的啊。。。。
while(~scanf("%d",&N)){
for(int i=;i<=N;i++)pre[i]=i,dep[i]=,s[i]=;
while(N--){
scanf("%s",c);
if(c[]=='M'){
scanf("%d%d",&x,&y);
merge(x,y);
}
else {
scanf("%d",&x);
int px=find(x);
// printf("s[%d]=%d %d\n",px,s[px],dep[x]);
printf("%d\n",s[px]-dep[x]-);
}
}
}
return ;
}

另一种解法超时:

 #include<stdio.h>
#include<string.h>
const int MAXN=;
int pre[MAXN],s[MAXN];//s数组存当前树的节点数;
int find(int x){
while(x!=pre[x])
x=pre[x];
return x;
}
void merge(int x,int y){
int f1,f2;
f1=find(x);f2=find(y);
if(f1!=f2){
pre[f2]=f1;
s[f1]+=s[f2];
}
}
int getdep(int x){
int s=;
while(x!=pre[x]){
x=pre[x];
s++;
}
return s;
}
int main(){
int N,x,y;
char c[];//定义成s了,错的啊。。。。
while(~scanf("%d",&N)){
for(int i=;i<=N;i++)pre[i]=i,s[i]=;
while(N--){
scanf("%s",c);
if(c[]=='M'){
scanf("%d%d",&x,&y);
merge(x,y);
}
else {
scanf("%d",&x);
int px=find(x);
int d=getdep(x);
printf("%d\n",s[px]-d-);
}
}
}
return ;
}