code vs 1743 反转卡片(splay)
2016-05-11 20:37
633 查看
1743 反转卡片
时间限制: 2 s空间限制: 256000 KB
题目等级 : 大师 Master
题解
查看运行结果
题目描述 Description
【dzy493941464|yywyzdzr原创】
小A将N张卡片整齐地排成一排,其中每张卡片上写了1~N的一个整数,每张卡片上的数各不相同。
比如下图是N=5的一种情况:3 4 2 1 5
接下来你需要按小A的要求反转卡片,使得左数第一张卡片上的数字是1。操作方法:令左数第一张卡片上的数是K,如果K=1则停止操作,否则将左数第1~K张卡片反转。
第一次(K=3)反转后得到:2 4 3 1 5
第二次(K=2)反转后得到:4 2 3 1 5
第三次(K=4)反转后得到:1 3 2 4 5
可见反转3次后,左数第一张卡片上的数变成了1,操作停止。
你的任务是,对于一种排列情况,计算要反转的次数。你可以假设小A不会让你操作超过100000次。
输入描述 Input Description
第1行一个整数N;
第2行N个整数,为1~N的一个全排列。
输出描述 Output Description
仅1行,输出一个整数表示要操作的次数。
如果经过有限次操作仍无法满足要求,输出-1。
样例输入 Sample Input
5
3 4 2 1 5
样例输出 Sample Output
3
数据范围及提示 Data Size & Hint
0<N≤300,000。
分类标签 Tags 点此展开
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #define N 3000011 using namespace std; int ch [2],fa ,key ,size ,a ,root; int rev ,sz,n; void update(int x) { size[x]=size[ch[x][0]]+size[ch[x][1]]+1; } int get(int x) { return ch[fa[x]][1]==x; } void pushdown(int x) { if (!rev[x]) return; rev[ch[x][0]]^=1; rev[ch[x][1]]^=1; swap(ch[x][0],ch[x][1]); rev[x]=0; } void rotate(int x) { pushdown(fa[x]); pushdown(x); int y=fa[x]; int z=fa[y]; int which=get(x); if (z) ch[z][ch[z][1]==y]=x; fa[x]=z; fa[y]=x; ch[y][which]=ch[x][which^1]; fa[ch[y][which]]=y; ch[x][which^1]=y; update(y); update(x); } void splay(int x,int tar) { for (int f;(f=fa[x])!=tar;rotate(x)) if (fa[f]!=tar) rotate(get(x)==get(f)?f:x); if (!tar) root=x; } int find(int x) { int now=root; while (true) { pushdown(now); if (x<=size[ch[now][0]]) now=ch[now][0]; else { int tmp=size[ch[now][0]]+1; if (tmp==x) return now; x-=tmp; now=ch[now][1]; } } } int build(int l,int r) { if (l>r) return 0; if (l==r) { ++sz; key[sz]=a[l]; size[sz]=1; return sz; } int now=++sz; int mid=(l+r)/2; ch[now][0]=build(l,mid-1); ch[now][1]=build(mid+1,r); fa[ch[now][0]]=now; fa[ch[now][1]]=now; size[now]=size[ch[now][0]]+size[ch[now][1]]+1; key[now]=a[mid]; return now; } int main() { freopen("a.in","r",stdin); scanf("%d",&n); a[1]=1000000000; for (int i=1;i<=n;i++) scanf("%d",&a[i+1]); a[n+2]=1000000000; root=build(1,n+2); for (int i=1;i<=100000;i++) { int t=key[find(2)]; if (t==1) { printf("%d\n",i-1); return 0; } int aa=find(1); int bb=find(t+2); splay(aa,0); splay(bb,aa); rev[ch[ch[root][1]][0]]^=1; } printf("-1\n"); }
相关文章推荐
- vim文档编辑
- 【C++ STL】三十分钟掌握STL
- Nodejs对postgresql基本操作的封装
- LeetCode:Power of Four
- 欢迎使用CSDN-markdown编辑器
- 区间调度问题
- 6--循环链表
- 初次接触Git(一)
- [置顶] 局部内部类
- Andorid之KeyguardManager的介绍
- Tengine 常用模块使用介绍
- 《剑指offer》-顺时针打印矩阵
- 优先队列(priority_queue)的cmp,POJ(2051)
- selenium的config.ini
- AutoLayout 使用详细
- B - Ignatius and the Princess IV——POJ
- 第十一周项目1.2— 点 圆 圆柱类族的设计
- B-树和B+树的应用:数据搜索和数据库索引
- 【模仿】对双机调试的学习
- C++第五次作业