第 117 节|T16 DP 优化与综合建模
建议 85 分钟:读题 5′、A 26′、B 39′、复测 15′。两题独立,自编,满分 100。
1. 考场策略
A 先守住合法前驱区间;B 先明说“恰好”以及不相邻是什么边界。能先写小数据参考,再优化。如分组只通过基本范围,据组别记分,不把“有思路”当成通过。
2. A|限距巡检(45 分)
从 1 开始,允许 i→j 当 1≤j−i≤W,必须到 n;每落到一个点就付 a[i],起点也计。输入 n W,再输入 n 个 a。1≤n≤2×10^5,1≤W≤n,|a[i]|≤10^9。输出最小总费用。分组:A1 n≤200(15);A2 W=1(10);A3 全范围含负值与窗口边界(20)。
5 2
3 -5 8 1 4
输出 3。路径 1→2→4→5。
3. B|恰好 K 个传感器(55 分)
一排 n 个位置,要选恰好 K 个且任意相邻点不能同选。选点 i 需付 a[i],可能为负。输入 n K 及 n 个 a。1≤n≤2000、0≤K≤n、|a[i]|≤10^9。输出最小费用;无解输出 Impossible。分组:B1 n≤12(15);B2 K≤1(10);B3 全范围,含无解、负值和恰好约束(30)。
5 2
3 -5 8 1 4
输出 −4(选 2、4)。
4. 限时提示
A:哪些没出队的候选才合法?
f[i] 依赖 f[j],合法 j 的区间为 [i−W,i−1]。先过期再查,先查再把 i 入队。若先入队,i 违反 i−1 的上界。
B:上一位置选了会有什么影响?
两层滚动、每层按恰好选的数量存两种末位状态。若选择当前位置,旧末位必须没选;不选时旧末位不限。
5. 盲测与迁移
A:n=1、a[1]=−7;再测 4 2 / 0 100 0 1。B:3 2 / 10 −100 10,和 2 2 / −5 −8。为何第 3 个测试不能因为 −100 很低就先选?
6. 对表补救
展开核对
A 分别是 −7、1;窗口边界 i−W 合法。B 分别是 20、Impossible;越过显式不可达做代价加法会造假值。复测 n=3、K=0、任意代价,答案永远 0。
7. 综合训练参考程序
A:滑窗最小 DP
f[1]=a[1]。窗口里较晚且值不大的候选可永久替代队尾较早且更贵的候选,因它更晚过期。以样例逐个算 3、−2、6、−1、3。O(n) 时间,O(n) 空间(队列只存活跃候选)。
#include <deque>
#include <iostream>
#include <utility>
using namespace std;
int main(){
ios::sync_with_stdio(false); cin.tie(nullptr);
int n,w;
if(!(cin>>n>>w)) return 0;
long long a,f;
cin>>f;
deque<pair<int,long long>> q{{1,f}};
for(int i=2;i<=n;++i){
cin>>a;
while(!q.empty() && q.front().first<i-w) q.pop_front(); // i−1 会在窗口内,且至少有一项。
f=q.front().second+a; // 查完才插入当前位置。
while(!q.empty() && q.back().second>=f) q.pop_back();
q.emplace_back(i,f);
}
cout<<f<<'\n';
}B:滚动前缀状态
no[k]、yes[k] 表示目前恰选 k 个且最后一位没选/已选时的最低代价。旧 no[k−1] 若可达才允许产生新 yes[k]。分开旧表和新表,两个分支都不会误读自己。O(n(K+1)) 时间,O(K+1) 空间。
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main(){
ios::sync_with_stdio(false); cin.tie(nullptr);
int n,K;
if(!(cin>>n>>K)) return 0;
const long long inf=4000000000000000000LL;
vector<long long> no(K+1,inf),yes(K+1,inf),nn(K+1),yy(K+1);
no[0]=0;
for(int i=1;i<=n;++i){
long long a; cin>>a;
for(int k=0;k<=K;++k){
nn[k]=min(no[k],yes[k]);
yy[k]=k>0 && no[k-1]!=inf?no[k-1]+a:inf; // 两个相邻点不能同时选。
}
no.swap(nn); yes.swap(yy);
}
long long ans=min(no[K],yes[K]);
if(ans==inf) cout<<"Impossible\n";
else cout<<ans<<'\n';
}