跳到正文

题解

题解:P17821 回層浮 / kaisou

Miss_SGT约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年10月30日
收录
2026年10月30日
更新
2026年11月11日
篇幅
约 3 分钟
获赞
1
题目
P17821

版本

  1. v1当前

有函数 fy(x)=∑i=1m∣x−y−ti∣f_{y}(x)=\sum_{i=1}^{m} |x-y-t_i|。显然对于任意 yy 这个函数都形如一个山谷。

发现对于任意 y1,y2y_1,y_2,fy1(x)f_{y_1}(x) 和 fy2(x)f_{y_2}(x) 形状都一样,即一个可以通过平移得到另一个。结合函数都形如山谷,易得任意两个函数只有 11 个交点,直接上李超树维护,查询 fy(x)f_{y}(x) 时二分 x−yx-y 在 tt 中的位置即可,复杂度 O(nlog⁡Vlog⁡m)O(n\log V\log m)。

C++
#include<bits/stdc++.h>
using namespace std;
const int N=3e5+5,L=-6e7,R=6e7;
int n,m,a[N],b[N],c[N];
#define ll long long
ll pre[N],suf[N],f[N];
const ll inf=1ll<<60;
struct fun{
	ll c,y;
	inline ll f(int x){
		x-=c;
		int o=lower_bound(b+1,b+m+1,x)-b;
		return suf[o]-pre[o-1]+1ll*x*(o-1-(m-o+1))+y;
	}
};
struct Tree{
	int ls,rs;
	fun v;
}t[N];
int root,tot;
#define mid ((l+r)>>1)
void change(int &p,int l,int r,fun v){
	if(!p) t[p=++tot].v=v,void();
	if(t[p].v.f(mid)<v.f(mid)) swap(t[p].v,v);
	if(l==r) return;
	if(t[p].v.f(l)<v.f(l)) change(t[p].ls,l,mid,v);
	else if(t[p].v.f(r)<v.f(r)) change(t[p].rs,mid+1,r,v);
}
ll query(int p,int l,int r,int x){
	if(!p) return -inf;
	ll res=t[p].v.f(x);
	if(l<r) res=max(res,x<=mid?query(t[p].ls,l,mid,x):query(t[p].rs,mid+1,r,x));
	return res;
}
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];
	for(int i=1;i<=n;++i) cin>>c[i];
	for(int i=1;i<=m;++i) cin>>b[i];
	sort(b+1,b+m+1);
	for(int i=1;i<=m;++i) pre[i]=pre[i-1]+b[i];
	for(int i=m;i;--i) suf[i]=suf[i+1]+b[i];
	f[1]=-c[1];
	for(int i=1;i<=n;++i){
		if(i>1) f[i]=-inf;
		f[i]=max(f[i],query(root,L,R,a[i])-c[i]);
		change(root,L,R,(fun){a[i],f[i]});
	}
	cout<<f[n];
	return 0;
} 
原文