Building Block
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4250 Accepted Submission(s): 1325
Problem Description
John are playing with blocks. There are N blocks (1 <= N <= 30000) numbered 1...N。Initially, there are N piles, and each pile contains one block. Then John do some operations P times (1 <= P <= 1000000). There are two kinds of operation:
M X Y : Put the whole pile containing block X up to the pile containing Y. If X and Y are in the same pile, just ignore this command.
C X : Count the number of blocks under block X
You are request to find out the output for each C operation.
M X Y : Put the whole pile containing block X up to the pile containing Y. If X and Y are in the same pile, just ignore this command.
C X : Count the number of blocks under block X
You are request to find out the output for each C operation.
Input
The first line contains integer P. Then P lines follow, each of which contain an operation describe above.
Output
Output the count for each C operations in one line.
Sample Input
6 M 1 6 C 1 M 2 4 M 2 6 C 3 C 4
Sample Output
1 0 2
题解:这一题还是比较有意义的,重点在于对并查集路径压缩的理解。
首先题目有两个操作,一个是合并,一个是查询,但是查询的内容是每个点下面的积木个数。
首先想到肯定是并查集,但是不好操作,因为合并之后上面集合里面的每个元素下面积木的个数都会发生改变,如果用并查集,我无法得知一个元素下面的元素,所以这里要多开几个数组。
我采用的方法是用d[i]来记录第i个点到根的距离,用cnt[i]来表示根节点i下面有多少个元素。这样我可以用cnt[father[k]]-cnt[k]-1来算出k元素下面有多少个积木。我在合并两个集合的时候,就先更新两个集合根的信息,不管下面的元素(因为在路径压缩的时候会被更新到,而且不用在意会被重复更新,因为每一个点只会被更新一次)。这样我们只需要递归进行更新就行了。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;
char s[2];
int P,x,y,d[30005],father[30005],cnt[30005];
int solve(int x)
{
int k;
if (father[x]==x) return x;
else k=solve(father[x]);
d[x]+=d[father[x]];
father[x]=k;
return k;
}
void union_(int x,int y)
{
int d1,d2;
d1=solve(x); d2=solve(y);
if (d1==d2) return ;
father[d2]=d1;
d[d2]=cnt[d1];
cnt[d1]+=cnt[d2];
}
int main()
{
memset(d,0,sizeof(d));
for (int i=0;i<=30000;i++) { father[i]=i; cnt[i]=1;}
scanf("%d",&P);
while (P--)
{
scanf("%s",s);
if (s[0]=='M')
{
scanf("%d%d",&x,&y);
union_(x,y);
}
if (s[0]=='C')
{
scanf("%d",&x);
solve(x);
printf("%d\n",cnt[father[x]]-d[x]-1);
}
}
return 0;
}