【POJ1988】Cube Stacking

Title: 【POJ1988】Cube Stacking

Title:

There are n cubes numbered 1~n and two operations, one is the move operation and the other is the count operation. The move operation is to let you move a pile of cubes containing x to the top of a pile of cubes containing y, and the count operation is to let you find the number of cubes under the cube numbered x.

Parse:

As soon as you see this question, it is easy to think of using a union-check set to do it, and this question is indeed done with a union-check set O(∩_∩)O~

First, let's consider the move operation. When you want to stack two piles of cubes together, you can update the father of the top of the bottom pile to the top of the top of the pile, which should be easy to think of.

So, how to find the number of squares under the cube numbered x?

We can use Under[x] to record how many squares are under the cube numbered x, so that we only need to output Under[x] when outputting.

However, it is impossible for us to continuously update Under[x], which is too complicated. Therefore, we can use an Up[] array to record the distance from each cube to the top of the stack of cubes where it is located. Just update the Under[] value at the top of each heap.

And this step can only be done by the way when merging, with almost no complexity.

Moreover, the update of the Up[] array is also very easy, just add a sentence Up[x]+=Up[f[x]] to the union search function getfa().

In this way, you can find that Under[x]=Under[getfa(x)]-Up[x], so just output Under[getfa(x)]-Up[x] when outputting.

code show as below:

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cmath>
#define max(x,y) (x>y?x:y)
#define min(x,y) (x<y?x:y)
#define N 30000
#define M 100000
using namespace std;
int m,f[N+5],Up[N+5],Under[N+5];
int read()
{
	int x=0,f=1;char ch=getchar();
	while((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
	if(ch=='-') f=-1,ch=getchar();
	while(ch>='0'&&ch<='9') (x*=10)+=ch-'0',ch=getchar();
	return x*=f;
}
void write(int x)
{
	if(x<0) putchar('-'),x=-x;
	if(x>9) write(x/10);
	putchar(x%10+'0');
}
int getfa(int x)//Union search function
{
	if(f[x]==x) return x;
	int fx=getfa(f[x]);
	Up[x]+=Up[f[x]],f[x]=fx;//Update f[] and Up[] two arrays
	return f[x];
}
intmain()
{
	for(int i=1;i<=N;i++) f[i]=i,Up[i]=Under[i]=0;//初始化
	m=read();
	for(int i=1;i<=m;i++)
	{
		char ch;
		cin>>ch;
		if(ch=='M')
		{
			int x=read(),y=read(),fx=getfa(x),fy=getfa(y);
			Up[fy]=Under[fx]+1,(Under[fx]+=Under[fy])++,f[fy]=fx;//Update the Under[] value at the top of the pile above and the following one father on top of piles
		}
		if(ch=='C')
		{
			int x=read(),fx=getfa(x);
			write(Under[fx]-Up[x]),putchar('\n');//输出
		}
	}
	return 0;
}




Copyright statement: Please indicate the address for reprinting

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325732229&siteId=291194637