http://www.51nod.com/contest/problem.html#!problemId=1364
#include<cstdio>
#include<cstring>
#include<string>
#include<map>
#include<iostream>
#include<vector>
#include<ctime>
#include<algorithm>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int MOD = 1000000007;
typedef pair<int,int> per;
#define mp(x,y) make_pair(x,y)
#define lc(x) node[x].lc
#define rc(x) node[x].rc
#define key(x) node[x].key
#define v(x) node[x].v
#define sz(x) node[x].sz
#define mx(x) node[x].mx
#define ps(x) node[x].ps
const int N = 300005;
const int M = 300005;
struct P
{
int lc,rc,v,sz,key,mx,ps;
}node[M];
int root,len;
char s[M];
int newnode(int v){
int id=++len;
lc(id)=rc(id)=0;
ps(id)=1;
mx(id)=v(id)=v;
key(id)=rand();
sz(id)=1;
return id;
}
void up(int x){
if(!x)return ;
mx(x)=v(x);
ps(x)=sz(lc(x))+1;
if(mx(lc(x))>mx(x))
{
mx(x)=mx(lc(x));
ps(x)=ps(lc(x));
}
if(mx(rc(x))>mx(x))
{
mx(x)=mx(rc(x));
ps(x)=sz(lc(x))+1+ps(rc(x));
}
sz(x)=sz(lc(x))+sz(rc(x))+1;
}
per split(int x,int n){
if(!n)return mp(0,x);
if(sz(x)==n)return mp(x,0);
int cnt=sz(lc(x));
if(cnt>=n){
per tp=split(lc(x),n);
lc(x)=tp.second;
up(x);
return mp(tp.first,x);
}
else{
per tp=split(rc(x),n-cnt-1);
rc(x)=tp.first;
up(x);
return mp(x,tp.second);
}
}
int merge(int l,int r){
if(!l||!r)return l+r;
if(key(l)<=key(r)){
rc(l)=merge(rc(l),r);
up(l);
return l;
}
else{
lc(r)=merge(l,lc(r));
up(r);
return r;
}
}
void insert(int k,int v){
per tp=split(root,k);
int nw=newnode(v);
root=merge(tp.first,nw);
root=merge(root,tp.second);
}
void del(int k){
per tp=split(root,k-1);
per tpp=split(tp.second,1);
root=merge(tp.first,tpp.second);
}
int mv;
int wk(int L,int R){
int rk;
per tp=split(root,L-1);
per tpp=split(tp.second,R-L+1);
rk=L-1+ps(tpp.first);
mv=mx(tpp.first);
root=merge(tpp.first,tpp.second);
root=merge(tp.first,root);
return rk;
}
int fr;
void dfs(int x)
{
if(!x)return ;
dfs(lc(x));
//if(fr)putchar(' ');
//fr=1;
printf("%d
",v(x));
dfs(rc(x));
}
inline int readT(){
int ret = 0; char c;
while(c = getchar(), c < '0' || c > '9') ; ret = c - 48;
while(c = getchar(), c >= '0' && c <= '9') ret = ret * 10 + c - 48;
return ret;
}
int a[N];
int main()
{
srand(time(NULL));
int n,k;
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++)
{
//scanf("%d",&a[i]);
a[i]=readT();
//insert(i-1,a[i]);
int nw=newnode(a[i]);
root=merge(root,nw);
}
for(int i=1;i<=n;i++)
{
int mx=a[i],p=i;
int rd=min(n,i+k);
int rk=wk(i,rd);
//printf("i:%d k:%d rk:%d mv:%d
",i,k,rk,mv);
if(rk==i)continue;
del(rk);
insert(i-1,mv);
k-=(rk-i);
// dfs(root);
}
dfs(root);
//puts("");
//for(int i=1;i<=n;i++)printf("%d
",a[i]);
return 0;
}