Building Block
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4548 Accepted Submission(s): 1408
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
Source
Recommend
#include <cstdio>
#include <iostream>
using namespace std;
const int MAXN = 30000 + 10;
int Fa[MAXN], Under[MAXN], Num[MAXN];
void Init()
{
for (int i = 0; i < MAXN; i++)
{
Fa[i] = i; //初始化并查集,自成一个连通分量
Num[i] = 1; //i是根节点,初始化以它为根的树共有1个节点
}
}
int Find(int x)
{
if (x == Fa[x]) return x;
int fa = Fa[x];
Fa[x] = Find(Fa[x]); //递归查找老祖宗
Under[x] += Under[fa]; //加上父亲的
return Fa[x];
}
void Union(int x, int y)
{
int tx = Find(x), ty = Find(y); //先查找两者的祖先
if (tx == ty) return;
Fa[tx] = ty; //合并
Under[tx] = Num[ty]; //tx下面多了Num[ty]个
Num[ty] += Num[tx]; //以ty为根的树多了Num[tx]个节点
Num[tx] = 0; //以tx为根的树没有结点(此时tx已经不是一个树的真正根节点)
}
int main()
{
int t, x, y;
char cmd[10];
Init();
scanf("%d", &t);
while (t--)
{
scanf("%s", cmd);
if (cmd[0] == 'C')
{
scanf("%d", &x);
Find(x);
printf("%d\n", Under[x]);
}
else
{
scanf("%d%d", &x, &y);
Union(x, y);
}
}
return 0;
}
//超时了的代码 不造怎么超了
#include<iostream>
#include<cstdio>
using namespace std;
int f[30005],vis[30005],down[30005],i,x,y,T;
char op[2];
int zbb(int x)
{
if(f[x]!=x)
{
down[x]+=down[f[x]];
return f[x]=zbb(f[x]);
}
else return x;
}
void hb(int x,int y)
{
int a=zbb(x),b=zbb(y);
if(a!=b)
{
f[a]=b;
down[a]=vis[b]; //x堆底下面的数量为y堆的数量
vis[b]+=vis[a]; //更新整个y堆加上合并x堆后的数量
}
}
void init(int n) //初始化
{
for(i=0;i<n;i++)
{
f[i]=i;
down[i]=0;
vis[i]=1;
}
}
int main()
{
scanf("%d",&T);
init(T);
while(T--)
{
scanf("%s",op);
if(op[0]=='M')
{
scanf("%d%d",&x,&y);
hb(x,y);
}
if(op[0]=='C')
{
scanf("%d",&x);
zbb(x);
printf("%d\n",down[x]);
}
}
return 0;
}