HDU 2475 Box
2015-10-16 13:37
323 查看
Box
Time Limit: 5000msMemory 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
相关文章推荐
- gdb使用
- Android AudioSystem模块分析
- 硅谷悄然而起的流行:在管理上干掉CEO!
- 利用jquery实现百度新闻导航菜单滑动动画
- CSS3学习笔记(5)—页面遮罩效果
- 下周我国数据密集公布 关注固定资产投资
- ubuntu14.04LTS下利用Laravel5.1框架写一个Blog
- 关于Viewpager加载网络图片显示不全
- iOS随机数
- CVE-2014-0196(马拉松赛跑bug)
- 关于内存 GetMemory( ) 笔试分析
- CVE-2014-0196(马拉松赛跑bug)
- Android开发UI设计资源汇总
- <LeetCode><Easy> 171 Excel Sheet Column Number
- ps aux命令显示的状态列中的状态(转)
- K - K.Bro Sorting
- 最新课程即将发布...
- 第五例:MQTT服务端及客户端学习
- 把数字显示成万元
- c#入门经典5~8章 与c++对比