a132中等至少需求的無限次方案 DP
TOI 2025/11 潛力組:餅乾促銷
允許超額取得,用尚缺包數避免多開上界。
解題思路
令 dp[c] 為至少取得 c 包的最少費用,dp[0]=0。若先購買方案 (A,B),剩下仍需至少 max(0,c−A−B) 包,因此 dp[c]=min(A+dp[max(0,c−A−B)])。按 c 遞增計算,所有依賴都較小,方案自然可以反覆使用。
取任一最優購買序列的第一個方案,剩餘方案必須滿足上述剩餘需求,故其費用不會低於轉移候選;反過來,每個候選都實際足夠 c 包,兩方向合起來證明最優。把超額需求截到 0,而非要求剛好 c 包,正是符合本題的關鍵。
Step-by-step animation
公開範例:5 包付 3、10 包付 5,需求 13
步驟 1 / 3
小需求可超買
需求 1 到 5 包時,一次五包方案就足夠。
dp[0]=0
dp[1]=3
dp[5]=3
- 方案
- (3,2)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, c;
cin >> n >> c;
vector<pair<int, int>> offers(n);
for (auto &[cost, count] : offers) {
int b;
cin >> cost >> b;
count = cost + b;
}
vector<int> dp(c + 1, 1000000000);
dp[0] = 0;
for (int need = 1; need <= c; ++need)
for (auto [cost, count] : offers)
dp[need] = min(dp[need], cost + dp[max(0, need - count)]);
cout << dp[c] << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。