[USACO08NOV]Buying Hay S
[USACO08NOV]Buying Hay S
题目描述
Farmer John is running out of supplies and needs to purchase H (1 <= H <= 50,000) pounds of hay for his cows.
He knows N (1 <= N <= 100) hay suppliers conveniently numbered 1..N. Supplier i sells packages that contain P_i (1 <= P_i <= 5,000) pounds of hay at a cost of C_i (1 <= C_i <= 5,000) dollars. Each supplier has an unlimited number of packages available, and the packages must be bought whole.
Help FJ by finding the minimum cost necessary to purchase at least H pounds of hay.
约翰的干草库存已经告罄,他打算为奶牛们采购 \(H(1 \leq H \leq 50000)\) 磅干草。
他知道 \(N(1 \leq N\leq 100)\) 个干草公司,现在用 \(1\) 到 \(N\) 给它们编号。第 \(i\) 公司卖的干草包重量为 \(P_i (1 \leq P_i \leq 5,000)\) 磅,需要的开销为 \(C_i (1 \leq C_i \leq 5,000)\) 美元。每个干草公司的货源都十分充足, 可以卖出无限多的干草包。
帮助约翰找到最小的开销来满足需要,即采购到至少 \(H\) 磅干草。
输入格式
* Line 1: Two space-separated integers: N and H
* Lines 2..N+1: Line i+1 contains two space-separated integers: P_i and C_i
输出格式
* Line 1: A single integer representing the minimum cost FJ needs to pay to obtain at least H pounds of hay.
样例 #1
样例输入 #1
2 15
3 2
5 3
样例输出 #1
9
提示
FJ can buy three packages from the second supplier for a total cost of 9.
解析
这是一道完完全全的完全背包,但还是有些不一样,这里不是单一的装入,还要考虑什么什么情况下有特殊情况
当重量大于等于h,小于等于h与价格最大值的和时,最小值都有可能出现,不仅存于重量等于h时
状态转移方程如下:
即少载i头奶牛再加上载i头奶牛的时间
AC代码
#include <bits/stdc++.h>
using namespace std;
int n,m,ans=1e9;
int a[100],b[100],dp[55005];
int main()
{
cin >> n >> m;
for(int i=1;i<=m+5000;i++)
{
dp[i]=1e9;//初始化,因为要找到一个最小值,dp[i]表示得到i磅的干草最少需要的钱数
}
for(int i=1;i<=n;i++)
{
cin >> a[i] >> b[i];
}
for(int i=1;i<=n;i++)
{
for(int j=a[i];j<=m+5000;j++)
{//注意循环结束为m+5000,因为你只购买m千克时花费的钱不一定是最少的,5000时一坨草质量的最大值
//完全背包
dp[j]=min(dp[j],dp[j-a[i]]+b[i]);
}
}
for(int i=m;i<=m+5000;i++)
{
ans=min(ans,dp[i]);//寻找哪一个既符合购买量,钱又最少
}
cout << ans;//直接输出即可
return 0;
}
本文来自小默的博客,转载请注明原文链接:https://www.cnblogs.com/momotrace/p/p2918.html