BZOJ1367: [Baltic2004]sequence

感觉非常神仙的一道题。
假设读入数组为A,所求数组为B。
我们先假设B中元素可以相同。
考虑如果A是一个单调上升的序列,我们直接取它本身就可以了。
如果A单调下降,那么B中每一位都显然是它的中位数。
那我们不妨把A中单调上升的区间拆成一个个单独的点,这样A就变成了若干下降的区间。
考虑用左偏树维护中位数。
不停加入A中每一个数作为一个堆,如果它前面的堆中位数>=它的,就向前合并。
但B中数不可以相同,怎么做?
把A中每个数都减去下标,这样B中相同的数加上下标后一定不同。

代码:

/**************************************************************
    Problem: 1367
    User: sckalrter
    Language: C++
****************************************************************/

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1000010;
int read(){
    int x=0,f=1; char ch=getchar();
    while (ch<'0'||ch>'9'){if (ch=='-') f=-1; ch=getchar();}
    while (ch>='0'&&ch<='9'){x=x*10+ch-'0'; ch=getchar();}
    return x*f;
}
struct hel{
    int dis,l,r,key,fa;
}h[N];
struct node{
    int l,r,sz,rt,val;
}st[N];
int a[N],top=0,b[N];
int merge(int u,int v){
    if (u==0||v==0) return u+v;
    if (h[u].key<h[v].key) swap(u,v);
    int &l=h[u].l,&r=h[u].r;
    r=merge(r,v);
    h[r].fa=u;
    if (h[l].dis<h[r].dis) swap(l,r);
    h[u].dis=h[r].dis+1;
    return u;
}
int del(int p){
    int l=h[p].l,r=h[p].r;
    h[l].fa=h[r].fa=0;
    int x=merge(l,r);
    h[p].l=h[p].r=0;
    return x;
}
int main(){
    int n=read();
    for (int i=1;i<=n;i++) a[i]=read(),a[i]-=i,h[i].key=a[i];
    h[0].dis=-1;
    st[++top]=(node){1,1,1,1,a[1]};
    for (int i=2;i<=n;i++){
        st[++top]=(node){i,i,1,i,a[i]};
        while (top>1&&st[top].val<st[top-1].val){
            top--;
            st[top].rt=merge(st[top].rt,st[top+1].rt);
            st[top].sz+=st[top+1].sz;
            st[top].r=st[top+1].r;
            while (st[top].sz>(st[top].r-st[top].l+2)/2){
                st[top].sz--;
                st[top].rt=del(st[top].rt);
            }
            st[top].val=h[st[top].rt].key;
        }
    }
    ll ans=0;
    for (int i=1,p=1;i<=n;i++){
        if (st[p].r<i) p++;
        b[i]=st[p].val+i; ans+=abs(st[p].val-a[i]);
    }
    printf("%lld\n",ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值