# Luogu P4331 [BOI2004]Sequence 数字序列

#include<iostream>
#include<cstdio>
#include<cmath>
#define R register int
#define ll long long
using namespace std;
namespace Luitaryi {
inline int g() { R x=0,f=1;
register char s; while(!isdigit(s=getchar())) f=s=='-'?-1:f;
do x=x*10+(s^48); while(isdigit(s=getchar())); return x*f;
} const int N=1000010;
int n; int ans[N]; ll anss;
int ls[N],rs[N],d[N],vl[N];
inline int merge(int x,int y) {
if(!x||!y) return x+y;
if(vl[x]<vl[y]) swap(x,y);
rs[x]=merge(rs[x],y);
if(d[ls[x]]<d[rs[x]]) swap(ls[x],rs[x]);
d[x]=d[rs[x]]+1; return x;
}
struct node {int l,r,rt,sz;}stk[N]; int top;
inline void main() {
d[0]=-1;
n=g();
for(R i=1;i<=n;++i) vl[i]=g()-i;
for(R i=1;i<=n;++i) {
++top,stk[top].l=stk[top].r=i,stk[top].rt=i,stk[top].sz=1;
while(top&&vl[stk[top-1].rt]>vl[stk[top].rt]) {
--top;
stk[top].rt=merge(stk[top].rt,stk[top+1].rt);
stk[top].r=stk[top+1].r;
stk[top].sz+=stk[top+1].sz;
while(stk[top].sz>(stk[top].r-stk[top].l+2)/2) {
--stk[top].sz;
stk[top].rt=merge(ls[stk[top].rt],rs[stk[top].rt]);
}
}
}
for(R i=1;i<=top;++i)
for(R j=stk[i].l;j<=stk[i].r;++j)
ans[j]=vl[stk[i].rt],anss+=abs(vl[j]-ans[j]);
printf("%lld\n",anss);
for(R i=1;i<=n;++i) printf("%d ",ans[i]+i);
}
} signed main() {Luitaryi::main(); return 0;}


2020.01.19

posted @ 2020-01-19 19:28  LuitaryiJack  阅读(155)  评论(0编辑  收藏  举报