题解:P16573 [USACO26Open] Haybale Stacks
(原文作者:Botao Yuan,由 GPT-5.4 Thinking 翻译)
题目分析
我们要求对于
个草垛。
现在考虑一个最优(或者接近最优)的雇佣顺序应当是什么样的。显然,我们通常应该尽量雇佣那些
问题在于
另一方面,如果我们离某个特殊值足够远,那么就应当反复选择最佳效率奶牛,直到到达某个需要考虑余数的阈值。事实证明,相对于当前考虑的特殊值,这个阈值是
关键结论
对于
其中
证明
考虑某个
如果它第一步就使用了最佳效率奶牛,那么显然有
现在假设在前
否则,假设这个解在前
只看前
对
由于
也就是
把这个不等式对子段中的所有奶牛求和,可以得到
因此,用
所以,对于所有
也就是说,只需要显式计算
你可能会注意到,这也和 Frobenius/Coin 问题有一定相似性。
部分解法:O(MS^3)
我们按
为了重新计算这个 DP 表,首先可以直接查询上一张 DP 表来得到初值。也就是说,对每个
共有
处理完
那么直接查表即可,答案为
否则,使用最佳效率奶牛
则答案为
总时间复杂度为
正解:O(MS^2)
我们还可以进一步优化 DP 重算的过程。注意到,当处理一头新的、阈值为
唯一新增的信息,就是这头刚刚加入的奶牛。因此,在用上一张表初始化完这
这样一来,每头奶牛只需要
参考代码
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll INF = 1e18;
const int S = 100;
void upd(ll& a, ll b) { a = min(a, b); }
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
int t; cin >> t;
while(t--) {
ll n; cin >> n;
vector<ll> a(n), oa(n);
for(int i = 0; i < n; i++) {
cin >> a[i];
oa[i] = i;
}
sort(oa.begin(), oa.end(), [&] (ll x, ll y) { return a[x] < a[y]; });
ll m; cin >> m;
vector<ll> l(m), s(m), v(m), o(m);
for(int i = 0; i < m; i++) {
cin >> l[i] >> s[i] >> v[i];
l[i]--;
o[i] = i;
}
sort(o.begin(), o.end(), [&] (ll x, ll y) { return l[x] < l[y]; });
int pl = 0;
vector<ll> dp(S * S, INF); dp[0] = 0;
vector<ll> best(S + 1, 1e15);
// computes expdp which is used to query
vector<ll> expdp;
int bsi = 1;
auto compute = [&] (int nsi) {
for(int si = 1; si <= S; si++) {
if(best[bsi] * si > bsi * best[si]) {
bsi = si;
}
}
expdp = dp;
for(int i = 0; i < expdp.size(); i++) {
if(i + nsi < expdp.size()) {
upd(expdp[i + nsi], expdp[i] + best[nsi]);
}
}
};
// uses expdp to query
auto query = [&] (ll x) {
ll d = x - pl;
ll t = max((d - (ll)expdp.size()) / bsi + 1, 0ll);
return t * best[bsi] + expdp[d - bsi * t];
};
int k = 0;
int lasts = 0;
vector<ll> ans(n);
for(int i : o) {
compute(lasts);
while(k < n && a[oa[k]] < l[i]) ans[oa[k]] = query(a[oa[k]]), k++;
vector<ll> ndp(S * S, INF);
for(int j = 0; j < S * S; j++) {
ndp[j] = query(l[i] + j);
}
for(int j = 1; j < s[i]; j++) upd(ndp[j], ndp[0] + v[i]);
upd(best[s[i]], v[i]);
lasts = s[i];
dp = ndp;
pl = l[i];
}
compute(lasts);
while(k < n) ans[oa[k]] = query(a[oa[k]]), k++;
for(ll i : ans) cout << i << " ";
cout << endl;
}
}