思路:这道题是并查集的应用,题目的意思是输入“M”的时候,再多输入两个数。表示前一个放在后一个的顶上。
方法:并查集的应用。
/*
这道题是给每个数定义tail[max],top[max],cnt[max];
max = 30000+5(这里的tail表示的是这个数的栈尾,
top表示的是这个数的栈顶,cnt表示这个数下面还有几个数)
我们用到了两个函数,一个函数用来更新tail与cnt,并返回栈尾的值
一个函数用来更新top。
*/
#include<stdio.h>
#include<string.h>
#define max 30000+5
int tail[max],top[max],cnt[max];
int count(int x){//更新tail与cnt
int temp;
temp = tail[x];
if(temp<0){
return x;
}
if(tail[temp]>=0){
tail[x] = count(temp);
cnt[x] = cnt[x]+cnt[temp];
}
return tail[x];
}
void move(int x,int y){
int tail_x,tail_y;//tail_x表示x的栈尾,tail_y表示y的栈尾
tail_x = count(x);//对tail_x的栈尾进行更新
tail_y = count(y);
tail[tail_x] = tail_y;//tail_x是x的栈尾,要将它置于y的上面,所以他的栈尾是y的栈尾。
count(top[tail_y]);//更新好x的栈尾后,通过x的栈尾,更新tail_x下面的cnt的值。
cnt[tail_x] = cnt[top[tail_y]]+1;
top[tail_y] = top[tail_x];
}
int main(){
int T,i,j,a,b;
char ch;
scanf("%d",&T);
memset(tail,-1,sizeof(tail));
memset(cnt,0,sizeof(cnt));
for(i=0;i<max;i++)
top[i]=i;
while(T--){
getchar();
scanf("%c",&ch);
getchar();
if(ch=='M'){
scanf("%d%d",&a,&b);
move(a,b);
}
else{
scanf("%d",&a);
count(a);
printf("%d\n",cnt[a]);
}
}
}