题解:P12179 DerrickLo's Game (UBC002B)

· · 题解

先分析这组数据:

1 2 3 4 5 6 7 6 5 4 3 2 1

询问 1~13 时,
如果使用操作2对整个区间进行操作,代价和为 13^2 ,即 169 。
如果使用操作2分别对 1\sim 7 和 7\sim 13 区间进行操作,代价和为 2\times 7^2 ,即 98 。

如果再次减少操作区间大小,代价和会继续减少。

既然如此,可以发现如果使用操作2,操作区间为 2 时花费代价和最小。
(因为 2\times 2^2 = 8 < 9 = 3^2 )

对于某个数要等于最大值,有两种方法:

  1. 通过操作1,增加到与区间最大值相同,代价为该值与最大值的差。
  2. 通过操作2,从左或右边直接将值改为最大值,代价为4。

所以,可以对每个数单独考虑,
与最大值相差4以内用操作1,
否则用操作2。

对于这组数据来说,
数 1,2,3 使用操作1,数 4,5,6,7 使用操作2 ,
代价和为 4\times 6 + 3\times 2 + 2\times 2 + 1\times 2 = 36 。

单点修改,区间查询,考虑用线段树。

线段树需要存该区间前4大的数和它们出现的次数。

时间复杂度 O(q\log{n}) 。

代码:

#include <bits/stdc++.h>

using namespace std;
const int N=200005;
struct tre
{
    int up[4],cnt[4],l,r;
}t[N<<2];
void update(tre * y,tre * l,tre * r)
{
    int lp=0,rp=0;
    for(int i=0;i<4;i++)
    {
        if(l->up[lp] == r->up[rp])
        {
            y->up[i]=l->up[lp];
            y->cnt[i]=l->cnt[lp]+r->cnt[rp];
            lp++,rp++;
        }else if(l->up[lp] > r->up[rp])
        {
            y->up[i]=l->up[lp];
            y->cnt[i]=l->cnt[lp];
            lp++;
        }else if(l->up[lp] < r->up[rp])
        {
            y->up[i]=r->up[rp];
            y->cnt[i]=r->cnt[rp];
            rp++;
        }
    }
}
int n,m;
int a[N];
void build(int l,int r,int p)
{
    t[p].l=l,t[p].r=r;
    if(l==r)
    {
        t[p].up[0]=a[l],t[p].cnt[0]=1;
    }else
    {
        int mid=(l+r)>>1;
        build(l,mid,p<<1);
        build(mid+1,r,p<<1|1);
        update(t+p,t+(p<<1),t+(p<<1|1));
    }
}
void change(int g,int x,int p)
{
    if(t[p].l==t[p].r)
    {
        t[p].up[0]=x,t[p].cnt[0]=1;
    }else
    {
        int mid=(t[p].l+t[p].r)>>1;
        if(g<=mid) change(g,x,p<<1);
        else change(g,x,p<<1|1);
        update(t+p,t+(p<<1),t+(p<<1|1));
    }
}
tre query(int l,int r,int p)
{
    if(t[p].l>=l&&t[p].r<=r)
    {
        return t[p];
    }else
    {
        int mid=(t[p].l+t[p].r)>>1;
        if(l<=mid&&r>mid)
        {
            tre li=query(l,r,p<<1),lf=query(l,r,p<<1|1),hp={};
            update(&hp,&li,&lf);
            return hp;
        }else if(l>mid)
        {
            return query(l,r,p<<1|1);
        }else if(r<=mid)
        {
            return query(l,r,p<<1);
        }
    }
}
int main()
{
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    build(1,n,1);
    while(m--)
    {
        int op,x,y;
        cin>>op>>x>>y;
        if(op==1)
        {
            change(x,y,1);
        }else
        {
            tre table=query(x,y,1);
            int tot=y-x+1,res=0;
            for(int i=0;i<4;i++)
            {
                if(table.up[0]-table.up[i]>=4)
                {
                    break;
                }
                tot-=table.cnt[i];
                res+=(table.up[0]-table.up[i])*table.cnt[i];
            }
            cout<<tot*4+res<<'\n';
        }
    }
    return 0;
}