跳到正文

题解

题解:P12179 DerrickLo's Game (UBC002B)

张景奕约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月16日
篇幅
约 5 分钟
题目
P12179

版本

  1. v1当前

先分析这组数据

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

询问 1~13 时,

如果使用操作2对整个区间进行操作,代价为 13213^2 ,即 169169

如果使用操作2分别对 1∼71\sim 7 和 7∼137\sim 13 区间进行操作,代价为 2×722\times 7^2 ,即 9898

。

。

。

通过观察,可以发现如果使用操作2,操作区间为 22 时花费代价最小(因为 2×22=8<9=322\times 2^2 = 8 < 9 = 3^2 )

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

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

所以,可以对每个数单独考虑

与最大值相差4以内用操作1

否则用操作2

对于这组数据来说

数 1,2,31,2,3 使用操作1,数 4,5,6,74,5,6,7使用操作2

代价为 4×6+3×2+2×2+1×2=364\times 6 + 3\times 2 + 2\times 2 + 1\times 2 = 36

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

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

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

代码

C++
#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;
}
原文