Description
Input
输入共两行,第一行为一个整数N,N表示物品的个数,1<=N<=100000。第二行为N个用空格隔开的正整数,表示N个物品最初排列的编号。
Output
输出共一行,N个用空格隔开的正整数P1,P2,P3…Pn,Pi表示第i次操作前第i小的物品所在的位置。 注意:如果第i次操作前,第i小的物品己经在正确的位置Pi上,我们将区间[Pi,Pi]反转(单个物品)。
Sample Input
6
3 4 5 1 6 2
3 4 5 1 6 2
Sample Output
4 6 4 5 6 6
HINT
Source
本来想写一波数据结构,放松心情。唉!
首先要将编号离散化,就是两次排序。之后维护一个pos数组,存储区间最小值的编号。
最后还要开一个栈,在伸展之前,将路径更新一遍。
#include<algorithm>
#include<iostream>
#include<cstdio>
using namespace std;
const int N=100005;
const int inf=1e9+7;
int n,rt,cnt,tp,ch[N][2],fa[N],sz[N],val[N],pos[N],mn[N],rev[N],s[N];
struct node
{
int pos,v;
}a[N];
bool cmp1(node c,node d)
{
if(c.v==d.v)
return c.pos<d.pos;
return c.v<d.v;
}
bool cmp2(node c,node d)
{
return c.pos<d.pos;
}
void pushup(int x)
{
pos[x]=x,mn[x]=val[x];
if(mn[ch[x][0]]<mn[x])
pos[x]=pos[ch[x][0]],mn[x]=mn[ch[x][0]];
if(mn[ch[x][1]]<mn[x])
pos[x]=pos[ch[x][1]],mn[x]=mn[ch[x][1]];
sz[x]=sz[ch[x][0]]+sz[ch[x][1]]+1;
}
void pushdown(int x)
{
if(rev[x])
{
rev[ch[x][0]]^=1,rev[ch[x][1]]^=1;
swap(ch[x][0],ch[x][1]);
rev[x]=0;
}
}
int build(int l,int r,int f)
{
if(l>r)
return 0;
int mid=(l+r)/2,x=++cnt;
ch[x][0]=build(l,mid-1,x);
ch[x][1]=build(mid+1,r,x);
fa[x]=f;
val[x]=a[mid].v;
pushup(x);
return x;
}
void rotate(int x,int &k)
{
int y=fa[x],z=fa[y],lc=ch[y][1]==x,rc=(lc^1);
if(k==y)
k=x;
else
ch[z][ch[z][1]==y]=x;
fa[x]=z,fa[y]=x,fa[ch[x][rc]]=y;
ch[y][lc]=ch[x][rc],ch[x][rc]=y;
pushup(y),pushup(x);
}
void splay(int x,int &k)
{
tp=0;
s[++tp]=x;
for(int i=x;fa[i];i=fa[i])
s[++tp]=fa[i];
for(int i=tp;i;i--)
pushdown(s[i]);
while(x!=k)
{
int y=fa[x],z=fa[y];
if(y!=k)
{
if((ch[y][0]==x)^(ch[z][0]==y))
rotate(x,k);
else
rotate(y,k);
}
rotate(x,k);
}
}
void split(int x,int y)
{
splay(x,rt),splay(y,ch[rt][1]);
}
int fnd(int x,int rnk)
{
pushdown(x);
if(rnk<=sz[ch[x][0]])
return fnd(ch[x][0],rnk);
if(rnk>sz[ch[x][0]]+1)
return fnd(ch[x][1],rnk-sz[ch[x][0]]-1);
return x;
}
int ask_mn(int l,int r)
{
int p=fnd(rt,l),q=fnd(rt,r);
split(p,q);
return pos[ch[q][0]];
}
int main()
{
scanf("%d",&n);
a[1].v=a[n+2].v=inf;
mn[0]=inf;
for(int i=2;i<=n+1;i++)
{
scanf("%d",&a[i].v);
a[i].pos=i;
}
sort(a+2,a+n+2,cmp1);
for(int i=2;i<=n+1;i++)
a[i].v=i-1;
sort(a+2,a+n+2,cmp2);
rt=build(1,n+2,0);
for(int i=1;i<=n;i++)
{
int x=ask_mn(i,n+2);
splay(x,rt);
printf("%d",sz[ch[x][0]]);
if(i!=n)
printf(" ");
int p=fnd(rt,i),q=fnd(rt,sz[ch[x][0]]+2);
split(p,q);
rev[ch[q][0]]^=1;
}
printf("\n");
return 0;
}