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款运动鞋,一个n件,总钱数为m,求不超过总钱数且每款鞋子至少买一双的情况下,使价值最大。如果 有一款买不到,就输出“Impossible"。
//分组背包的一个变形问题。传统的分组背包,一组最多只能取一个。而题目说的是,至少取一个。所以这是一个带分组的0/1背包问题。
本题的关键在于初始化,如果我们一开始把dp初始化为0的话,当我们买的鞋子的价值都是0的时候,就无法区分是买不全那几款鞋子还是能买全但最大价值是0。
dp[i][k] //表示不选
dp[i-1][k-v[j]]+w[j]//表示在本组选一个,但是由于数组一开始赋值为-1了,所以这个由i-1 推出
dp[i][k-v[i]]+w[i]//表示选择当前,不是第一次选了。
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int dp[105][10005];
int v[N],w[N];
int a[N];
int n,m,k;
int main()
{
while(~scanf("%d %d %d",&n,&m,&k))
{
for(int i=0;i<n;i++) cin>>a[i]>>v[i]>>w[i];
for(int i=0;i<=k;i++)
for(int j=0;j<=m;j++)
{
if(i==0) dp[i][j]=0;
else dp[i][j]=-1;
}
for(int i=1;i<=k;i++)
for(int j=0;j<n;j++)
{
if(a[j]==i)
{
for(int p=m;p>=v[j];p--) dp[i][p]=max(dp[i][p],max(dp[i-1][p-v[j]]+w[j],dp[i][p-v[j]]+w[j]));
}
}
if(dp[k][m]>=0 )printf("%d\n",dp[k][m]);
else printf("Impossible\n");
}
}