您的位置:首页 > 其它

HDU 2475 Box

2015-10-16 13:37 323 查看

Box

Time Limit: 5000ms
Memory Limit: 32768KB
This problem will be judged on HDU. Original ID: 2475
64-bit integer IO format: %I64d Java class name: Main

There are N boxes on the ground, which are labeled by numbers from 1 to N. The boxes are magical, the size of each one can be enlarged or reduced arbitrarily.
Jack can perform the “MOVE x y” operation to the boxes: take out box x; if y = 0, put it on the ground; Otherwise, put it inside box y. All the boxes inside box x remain the same. It is possible that an operation is illegal, that is, if box y is contained (directly or indirectly) by box x, or if y is equal to x.
In the following picture, box 2 and 4 are directly inside box 6, box 3 is directly inside box 4, box 5 is directly inside box 1, box 1 and 6 are on the ground.

#include <bits/stdc++.h>
using namespace std;
const int maxn = 300010;
struct LCT{
int fa[maxn],ch[maxn][2],parent[maxn];
void init(){
memset(fa,0,sizeof fa);
memset(ch,0,sizeof ch);
}
void rotate(int x,int kd){
int y = fa[x];
ch[y][kd^1] = ch[x][kd];
fa[ch[x][kd]] = y;
fa[x] = fa[y];
ch[x][kd] = y;
fa[y] = x;
if(fa[x]) ch[fa[x]][y == ch[fa[x]][1]] = x;
}
void splay(int x,int goal = 0){
int y = x;
while(fa[y]) y = fa[y];
if(x != y){
parent[x] = parent[y];
parent[y] = 0;
while(fa[x] != goal){
if(fa[fa[x]] == goal) rotate(x,x == ch[fa[x]][0]);
else{
int y = fa[x],z = fa[y],s = (y == ch[z][0]);
if(x == ch[y][s]){
rotate(x,s^1);
rotate(x,s);
}else{
rotate(y,s);
rotate(x,s);
}
}
}
}
}
void access(int x){
for(int y = 0; x; x = parent[x]){
splay(x);
fa[ch[x][1]] = 0;
parent[ch[x][1]] = x;
ch[x][1] = y;
fa[y] = x;
parent[y] = 0;
y = x;
}
}
int GetRoot(int x){
access(x);
splay(x);
while(ch[x][0]) x = ch[x][0];
return x;
}
void cut(int x){
access(x);
splay(x);
parent[ch[x][0]] = parent[x];
parent[x] = 0;
fa[ch[x][0]] = 0;
ch[x][0] = 0;
}
void join(int x,int y){
if(!y) cut(x);
else{
access(y);
splay(y);
int z = x;
while(fa[z]) z = fa[z];
if(z != y){
cut(x);
parent[x] = y;
}
}
}
}lct;
int main(){
int n,m,u,v;
char op[10];
bool flag = false;
while(~scanf("%d",&n)){
lct.init();
if(flag) putchar('\n');
for(int i = 1; i <= n; ++i)
scanf("%d",&lct.parent[i]);
scanf("%d",&m);
while(m--){
scanf("%s%d",op,&u);
if(op[0] == 'Q') printf("%d\n",lct.GetRoot(u));
else{
scanf("%d",&v);
lct.join(u,v);
}
}
flag = true;
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: