BZOJ 1367: [Baltic2004]sequence

题意

给出n个数a[1..n],要求求n个数b[1..n],满足b是严格递增且∑abs(a[i]−b[i])最小。
n<=1000000

分析

可以参考黄源河dalao的论文左偏树特点及其应用

一看题的时候没什么思路,但我们可以按照从一般到特殊的思想去思考这道题。
若a[1]<=a[2]<=…<=a[n],那么b[i]=a[i]则一定是最优答案。
若a[1]>=a[2]>=…>=a[n],那么b[1]=b[2]=…=b[n]=a[n/2+1]也就是中位数一定是最优答案。
那么我们可以考虑把整个序列分成m段,每段的最优解都是其中位数,那么我们只要保证这m段的中位数单调递增即可。
那么假设现在处理到第i个数,我们把a[i]设为单独的一段,那么这一段的答案就是a[i],如果a[i] < w[m-1]则把第m段和第m-1段合并即可。
维护中位数的方法是:用左偏树(大根堆)维护这一段的值,如果左偏树的节点数大于区间长度/2则删除树顶元素。

代码

#include <bits/stdc++.h>

const int N = 1000005;

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 Note
{
    int l,r,size;
    int root;
}w[N];

struct Tree
{
    int l,r;
    int key,dis;
}t[N];

int merge(int x,int y)
{
    if (!x)
        return y;
    if (!y)
        return x;
    if (t[y].key > t[x].key)
        std::swap(x,y);
    t[x].r = merge(t[x].r, y);
    if (t[t[x].l].dis < t[t[x].r].dis)
        std::swap(t[x].l, t[x].r);
    t[x].dis = t[t[x].r].dis + 1;
    return x;
}

int pop(int x)
{
    return merge(t[x].l, t[x].r);
}

int a[N];

int main()
{
    int n = read();
    for (int i = 1; i <= n; i++)
    {
        a[i] = read();
        a[i] -= i;
    }
    int m = 1;
    t[0].dis = -1;
    w[1].root = 1, w[1].size = 1, w[1].l = w[1].r = 1;
    t[1].dis = 0, t[1].key = a[1];
    for (int i = 2; i <= n; i++)
    {
        w[++m].root = i, w[m].size = 1, w[m].l = w[m].r = i;
        t[i].dis = 0, t[i].key = a[i];
        while (t[w[m].root].key < t[w[m - 1].root].key && m > 1)
        {
            w[m - 1].size += w[m].size, w[m - 1].r = w[m].r;
            w[m - 1].root = merge(w[m - 1].root, w[m].root);
            m--;
            while (w[m].size > (w[m].r - w[m].l + 2) >> 1)
            {
                w[m].root = pop(w[m].root);
                w[m].size--;
            }
        }
    }
    long long ans = 0;
    for (int i = 1; i <= m; i++)
        for (int j = w[i].l; j <= w[i].r; j++)
            ans += abs(a[j] - t[w[i].root].key);
    printf("%lld\n",ans);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值