Description
现在假设你一共有资金n元,而市场有m种大米,每种大米都是袋装产品,其价格不等,并且只能整袋购买。
请问:你用有限的资金最多能采购多少公斤粮食呢?
Input
输入数据首先包含一个正整数C,表示有C组测试用例,每组测试用例的第一行是两个整数n和m(1<=n<=100, 1<=m<=100),分别表示经费的金额和大米的种类,然后是m行数据,每行包含3个数p,h和c(1<=p<=20,1<=h<=200,1<=c<=20),分别表示每袋的价格、每袋的重量以及对应种类大米的袋数。
Output
对于每组测试数据,请输出能够购买大米的最多重量,你可以假设经费买不光所有的大米,并且经费你可以不用完。每个实例的输出占一行。
Sample Input
1
8 2
2 100 4
4 100 2
Sample Output
400
Solution
多重背包板题,包含了01背包、完全背包。注意:
- dp[]的初始化
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn = 111, INF = 0x3f3f3f3f;
int dp[maxn];
int total_cost, total_kind;
struct Rice
{
int weight, cost, num;
};
Rice arr[maxn];
void zero_pack(int cost, int weight)
{
for (int i = total_cost; i - cost >= 0; i--)
dp[i] = max(dp[i], dp[i - cost] + weight);
}
void complete_pack(int cost, int weight)
{
for (int i = cost; i <= total_cost; i++)
dp[i] = max(dp[i], dp[i - cost] + weight);
}
void multiple_pack(int cost, int weight, int num)
{
//如果大于等于金额,就按完全背包处理(此时相当于不限定袋数)
if (cost * num >= total_cost)
{
complete_pack(cost, weight);
return;
}
//打包成1 2 4 8 ...份
int k = 1;
while (k < num)
{
zero_pack(k * cost, k * weight);
num -= k;
k << 1;
}
//处理剩下的物品
zero_pack(num * cost, num * weight);
}
int main()
{
// freopen("in.txt", "r", stdin);
int T;
scanf("%d", &T);
while (T--)
{
scanf("%d%d", &total_cost, &total_kind);
for (int i = 1; i <= total_kind; i++)
scanf("%d%d%d", &arr[i].cost, &arr[i].weight, &arr[i].num);
// 多重背包
memset(dp, 0, sizeof(dp));
dp[0] = 0;
for (int i = 1; i <= total_kind; i++)
multiple_pack(arr[i].cost, arr[i].weight, arr[i].num);
printf("%d\n", dp[total_cost]);
}
return 0;
}