题目:http://acm.hit.edu.cn/hoj/problem/view?id=2385
并查集的巧妙应用,注意是多组测试数据,Poj上相同一题是一组测试数据。
开一个数组deep,表示这个结点离根结点的距离,每次移动的时候,只需要更新一次要放上去的立方体的个数,就是移动后该结点到根结点的距离。查询的时候,只需要用总数-离根结点的距离然后-1即可。
注意findset()更新时deep的顺序。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <stack>
#include <queue>
#include <map>
using namespace std;
int father[30005];
int son[30005];
int deep[30005];
int findset(int a)
{
if(a == father[a])
{
return a;
}
//注意顺序
int temp = father[a];
father[a] = findset(temp);
deep[a] += deep[temp];
return father[a];
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
int p;
while(scanf(" %d",&p)!=EOF)
{
for(int i=1; i<30005; i++)
{
father[i] = i;
son[i] = 1;
deep[i] = 0;
}
char c;
int x,y;
for(int i=0; i<p; i++)
{
scanf(" %c",&c);
if(c == 'M')
{
scanf(" %d %d",&x,&y);
x = findset(x);
y = findset(y);
if(x!=y)
{
father[y] = x;
//顺序不要颠倒
deep[y] = son[x];
son[x] += son[y];
}
}
else if(c == 'C')
{
int d;
scanf(" %d",&d);
printf("%d\n",son[findset(d)] - deep[d] - 1);
}
}
}
return 0;
}