跳到正文

题解

题解:P7294 [USACO21JAN] Minimum Cost Paths P

Purslane约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 4 分钟
题目
P7294

版本

  1. v1当前

Solution

设 dpx,ydp_{x,y} 表示,从 (1,1)(1,1) 走到 (x,y)(x,y) 的代价。

则有:

dpx,y=min⁡{dpx,y−1+x2,dpx−1,y+cy}dp_{x,y} = \min\{dp_{x,y-1}+x^2,dp_{x-1,y}+c_y\}

动态改变 yy,维护 dp∗,ydp_{*,y} 的变化。

首先,默认走第一条,也就是默认全局加下标的平方。

使用数学归纳法容易发现,dp∗,ydp_{*,y} 始终是凸的。所以你加上下标的平方之后还是凸的。

这时候引入第二种操作。发现只需要找到差分数组第一个 ≥cy\ge c_y 的位置,将他之后的位置赋值为 cyc_y。

直观的想法是使用线段树维护这个过程。但是考虑值域很大,要动态开点,会爆空间。

注意每次都是给一段后缀赋值,所以我们可以将差分数组拆成若干段,每一段的值都是 cy+(t−y)(2x+1)c_y + (t-y)(2x+1) 型,其中 tt 是我们当前考虑到的列的标号。

直接维护所有端点即可,只需要一个栈,在上面二分、求和即可。

我比较懒,为了避免细节直接先二分再弹栈,所以是 O(nlog⁡2n)O(n\log^2 n) 的。。

C++
#include<bits/stdc++.h>
#define int long long
#define ffor(i,a,b) for(int i=(a);i<=(b);i++)
#define roff(i,a,b) for(int i=(a);i>=(b);i--)
using namespace std;
const int MAXN=2e5+10;
int n,m,q,c[MAXN],tot,id[MAXN],t[MAXN],val[MAXN],pre[MAXN],ans[MAXN];
int sum(int l,int r) {return (r+1)*(r+1)-l*l;}
int calc(int pos,int qt) {
	if(pos==0) return 0;
	int qid=upper_bound(t+1,t+tot+1,pos)-t-1;
	return qt*sum(1,pos)+pre[qid-1]+c[id[qid]]*(pos-t[qid]+1)-id[qid]*sum(t[qid],pos);
}
int Calc(int pos,int qt) {
	int qid=upper_bound(t+1,t+tot+1,pos)-t-1;
	return c[id[qid]]+(qt-id[qid])*(2*pos+1);
}
vector<pair<int,int>> qr[MAXN];
signed main() {
	ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
	cin>>n>>m;
	ffor(i,1,m) cin>>c[i];
	cin>>q;
	ffor(i,1,q) {int x,y;cin>>x>>y,qr[y].push_back({x,i});}
	t[++tot]=1,id[tot]=1;
	for(auto pr:qr[1]) ans[pr.second]=calc(pr.first-1,1);
	ffor(i,2,m) {
		if(c[id[tot]]+(i-id[tot])*(2*n-1)>c[i]) {
			int ans=-1,l=1,r=n-1;
			while(l<=r) {
				int mid=(l+r)>>1;
				if(Calc(mid,i)>c[i]) ans=mid,r=mid-1;
				else l=mid+1;
			}
			while(tot&&t[tot]>=ans) tot--;
			if(tot==0) ++tot,t[tot]=1,id[tot]=i,pre[tot]=0;
			else pre[tot]=pre[tot-1]+c[id[tot]]*(ans-t[tot])-id[tot]*sum(t[tot],ans-1),++tot,t[tot]=ans,id[tot]=i,pre[tot]=0;
		}
		for(auto pr:qr[i]) ans[pr.second]=calc(pr.first-1,i)+i-1;
	}
	ffor(i,1,q) cout<<ans[i]<<'\n';
	return 0;
}
原文