Luogu P4331 [BOI2004] Sequence number sequence

Thinking questions OrzOrz;

In order to facilitate thinking (think) , we can \ (a_i \) minus \ (i \) , the strict conditions for increasing incrementally into non-stringent conditions.

First, if \ (a \) increase, we take \ (b_i = a_i \) can be; if (a \) \ decreasing, we take \ (b \) is \ (a \) of the median can be (both points cards).

This question and can use a similar method: We first element as each separate section, which assumes \ (= a_i B_i \) ; if \ (b_ {i-1} \ leq b_i \) is valid; If \ (b_ {i-1} > b_i \) then we \ (I \) thrown on to section; thus produces many segments (not necessarily the case), we only need to be maintained in place and the stack the number can be.

#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.18

Guess you like

Origin www.cnblogs.com/Jackpei/p/12215312.html