[CODEVS1743]反转卡片(splay)
2016-05-11 20:31
369 查看
题目描述
传送门题解
splay模板题。代码
#include<iostream> #include<cstring> #include<cstdio> using namespace std; const int max_n=3e5+5; const int INF=1e9; int n,root,sz,cnt; int a[max_n],f[max_n],ch[max_n][2],size[max_n],key[max_n],delta[max_n]; bool flag; inline int get(int x) { return ch[f[x]][1]==x; } inline void update(int x) { if (x) { size[x]=1; if (ch[x][0]) size[x]+=size[ch[x][0]]; if (ch[x][1]) size[x]+=size[ch[x][1]]; } } inline void pushdown(int x) { if (x&&delta[x]) { swap(ch[x][0],ch[x][1]); if (ch[x][0]) delta[ch[x][0]]^=1; if (ch[x][1]) delta[ch[x][1]]^=1; delta[x]=0; } } inline int build(int l,int r,int fa) { int mid=(l+r)>>1; if (l>r) return 0; int now=++sz; key[now]=a[mid]; f[now]=fa; delta[now]=0; int lch=build(l,mid-1,now); int rch=build(mid+1,r,now); ch[now][0]=lch; ch[now][1]=rch; update(now); return now; } inline void rotate(int x) { pushdown(f[x]); pushdown(x); int old=f[x],oldf=f[old],which=get(x); ch[old][which]=ch[x][which^1]; f[ch[old][which]]=old; ch[x][which^1]=old; f[old]=x; if (oldf) ch[oldf][ch[oldf][1]==old]=x; f[x]=oldf; update(old); update(x); } inline void splay(int x,int tar) { for (int fa;(fa=f[x])!=tar;rotate(x)) if (f[fa]!=tar) rotate((get(x)==get(fa))?fa:x); if (!tar) root=x; } inline int find(int x) { int now=root; while (1) { pushdown(now); if (ch[now][0]&&size[ch[now][0]]>=x) now=ch[now][0]; else { int temp=1; if (ch[now][0]) temp+=size[ch[now][0]]; if (x<=temp) return now; x-=temp; now=ch[now][1]; } } } int main() { scanf("%d",&n); a[1]=-INF; a[n+2]=INF; for (int i=1;i<=n;++i) scanf("%d",&a[i+1]); root=build(1,n+2,0); flag=false; while (cnt<100000) { int aa=find(2); int t; if ((t=key[aa])!=1) { cnt++; int aa=find(1); int bb=find(t+2); splay(aa,0); splay(bb,aa); delta[ch[ch[root][1]][0]]^=1; } else { flag=true; break; } } if (flag) printf("%d\n",cnt); else printf("-1\n"); }
总结
find不要忘了pushdown相关文章推荐
- LeetCode Everyday: 1. Two Sum
- android基础学习之fragment+viewpager+fragment事件听
- 第十一周项目1.1—点 圆 圆柱类族的设计
- 自定义控件——画圆圈
- C语言深度解剖学习笔记
- Qt显示中文和使用中文路径
- LeetCode:Move Zeroes
- 关于HOG特征的一个Python代码
- youi软件测试计划
- 中英文环境转变
- cf76e Points 【降维】
- UFLDL 11 卷积与池化 convolution pooling
- NYOJ 832合并游戏(状态压缩dp)
- 图 邻接链表的拓扑排序
- asp.net AdRotator控件
- mount命令详解
- 模块hashlib
- ubuntu 安装 右键终端 eclpse 远程终端
- Mysql常用函数
- Android程序报错,不能再console捕捉并定位到错误行,怎么办?