题目:http://poj.org/problem?id=1988
/*
带权并查集的题目。
father[x] 为x的父亲节点(x所在stack顶端的cube)
weight[x] 为x所在stack包含的cube数量
up[x] 为在x上方的cube的数量
则x之下的cube数应为weight[find(x)]-up[x]-1
即用x的父亲节点所在stack的cube数减去x上面的cube数,再减去x自身
*/
#include<iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
const int maxn = 30005;
int father[maxn];
int up[maxn];
int weight[maxn];
void make_set(int n){
for(int i =1;i <= n;i++){
father[i] = i;
up[i] = 0;
weight[i] = 1;
}
}
int find_set(int x){
if(father[x]== x)
return x;
int p = father[x] ;//递归的求每个结点上面的个数
father[x] = find_set(father[x]) ;
up[x] += up[p];
return father[x];
}
void union_set(int x,int y){
x =find_set(x);
y =find_set(y);
if(x ==y)
return;
father[y] =x;
up[y]=weight[x];
weight[x]+=weight[y];
}
int main(){
int p;
scanf("%d",&p);
make_set(maxn);
char str;
while(p--){
cin>>str;
if(str == 'M'){
int x,y;
scanf("%d%d",&x,&y);
union_set(x,y);
}
else{
int x;
scanf("%d",&x);
int ans = weight[find_set(x)] - up[x] - 1;
printf("%d\n",ans);
}
}
return 0;
}