题解:
左偏树
每一次合并它的儿子大根堆
每一次大于m就弹出
代码:
#include<bits/stdc++.h> using namespace std; const int N=1000005; long long ans; int rt[N],cnt,r[N],c[N][2],dist[N],val[N],tot,size[N],n,a[N],l[N]; int merge(int x,int y) { if (!x||!y)return x+y; if (val[x]<val[y])swap(x,y); c[x][1]=merge(c[x][1],y); size[x]=size[c[x][0]]+size[c[x][1]]+1; if (dist[c[x][0]]<dist[c[x][1]])swap(c[x][0],c[x][1]); dist[x]=dist[c[x][1]]+1; return x; } void pop(int &x){x=merge(c[x][0],c[x][1]);} int newnode(int x) { val[++tot]=x; size[tot]=1; c[tot][0]=c[tot][1]=dist[tot]=0; return tot; } int main() { scanf("%d",&n); for (int i=1;i<=n;i++)scanf("%d",&a[i]),a[i]-=i; for (int i=1;i<=n;i++) { rt[++cnt]=newnode(a[i]); l[cnt]=r[cnt]=i; while (cnt>1&&val[rt[cnt-1]]>val[rt[cnt]]) { cnt--; rt[cnt]=merge(rt[cnt],rt[cnt+1]); r[cnt]=r[cnt+1]; while (size[rt[cnt]]*2>r[cnt]-l[cnt]+2)pop(rt[cnt]); } } for (int i=1;i<=cnt;i++) { int t=val[rt[i]]; for (int j=l[i];j<=r[i];j++) ans+=abs(t-a[j]); } printf("%lld",ans); }