分组背包
分组背包就是把n种物品分成s组,每种物品都有自己的体积和价值,一个背包体积为v,在背包能装下的情况下选择出价值最大的组合。
思路就是开一个二维数组,行代表这s组,每一行都是一个优化的滚动数组。抓住每一组,遍历所有的n中物品,如果是这一组的,就对他进行操作。
After months of hard working, Iserlohn finally wins awesome amount of scholarship. As a great
zealot of sneakers, he decides to spend all his money on them in a sneaker store.
There are several brands of sneakers that Iserlohn wants to collect, such as Air Jordan and Nike Pro. And each brand has released various products. For the reason that Iserlohn is definitely a sneaker-mania, he desires to buy at least one product for each brand.
Although the fixed price of each product has been labeled, Iserlohn sets values for each of them based on his own tendency. With handsome but limited money, he wants to maximize the total value of the shoes he is going to buy. Obviously, as a collector, he won’t buy the same product twice.
Now, Iserlohn needs you to help him find the best solution of his problem, which means to maximize the total value of the products he can buy.
Input
Input contains multiple test cases. Each test case begins with three integers 1<=N<=100 representing the total number of products, 1 <= M<= 10000 the money Iserlohn gets, and 1<=K<=10 representing the sneaker brands. The following N lines each represents a product with three positive integers 1<=a<=k, b and c, 0<=b,c<100000, meaning the brand’s number it belongs, the labeled price, and the value of this product. Process to End Of File.
Output
For each test case, print an integer which is the maximum total value of the sneakers that Iserlohn purchases. Print “Impossible” if Iserlohn’s demands can’t be satisfied.
Sample Input
5 10000 3
1 4 6
2 5 7
3 4 99
1 55 77
2 44 66
Sample Output
255
这个题是分组背包中限制了每一组都必须至少买一个物品,并且每个物品最多买一件,所以s组行,每一行都是一个01背包的滚动数组。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int dp[15][10005];//每行代表一组, 每一行都是这一组的滚动数组
int f[105], v[105], w[105];
int my_max(int a, int b, int c)
{//返回a, b, c中的最大值
int t=a>b?a:b;
return t>c?t:c;
}
int main()
{
int n, m, s;
while (scanf("%d%d%d", &n, &m, &s)!=EOF){
for (int i=1; i<=n; i++)
scanf("%d%d%d", &f[i], &v[i], &w[i]);
memset(dp, -1, sizeof(dp));//-1表明前i组的j价值还没买东西
for (int j=0; j<=m; j++)
dp[0][j] = 0;//因为下面会用到上一层,所以0行全0
for (int i=1; i<=s; i++){//遍历每一组
for (int j=0; j<=n; j++){//遍历n个物品
if (f[j]==i){//如果这一个物品是这个组的
for (int k=m; k>=v[j]; k--)//进入滚动数组
dp[i][k]=my_max(dp[i][k], dp[i][k-v[j]]+w[j], dp[i-1][k-v[j]]+w[j]);
//这个点,这个组腾出v[j]加入这个物品,前i-1个组腾出v[j]加入这个物品
}
}
}
if (dp[s][m]<0)
printf("Impossible\n");
else
printf("%d\n", dp[s][m]);
}
return 0;
}