I love sneakers!
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7557 Accepted Submission(s): 3044
Problem Description
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
题意:
现在有n种牌子的鞋子,每种品牌有一些不同的鞋,每双鞋子都有一个特定的权值和价格,现在要求每种品牌的鞋子都至少收集一双,有一定量的钱,问获得的最大的权值是多少。
解题思路:
背包九讲讲的是每组至多选一个,此题是每组至少选一个,所以dp[i][j]代表前i组money为j最多买到的价值。初始化方面要注意,先将全部初始化为-1表示不存在,为了计算从第一维到第k维,要将dp[0]初始化为0。然后先枚举每一组,再枚举每一组的鞋子,最后一层是金钱,因为可以转化为01背包,所以逆序枚举。接着判断dp[i][l-x[i][j].p]是不是等于-1,如果不是,那么就可以利用这一个dp推导出现在的dp[i][l]。
也就是if(dp[i][l-x[i][j].p]!=-1)
dp[i][l]=max(dp[i][l],dp[i][l-x[i][j].p]+x[i][j].v);
if(dp[i-1][l-x[i][j].p]!=-1)
dp[i][l]=max(dp[i][l],dp[i-1][l-x[i][j].p]+x[i][j].v);
判断顺序很重要(先判断当前这一行是不是已经有被利用了的,在判断上一行)。
//分组背包
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int cost[105];
int kind[105];
int val[105];
int dp[105][10005];
int main()
{
int n,m,k;
while(~scanf("%d%d%d",&n,&m,&k))
{
memset(dp,-1,sizeof(dp));
for(int i=0;i<=m;i++)
dp[0][i]=0;
for(int i=1;i<=n;i++)
{
cin>>kind[i]>>cost[i]>>val[i];
}
for(int i=1;i<=k;i++)
{
for(int j=1;j<=n;j++)
{
if(kind[j]==i)
{
for(int voc=m;voc>=cost[j];voc--)
{
dp[i][voc]=max(max(dp[i][voc],dp[i][voc-cost[j]]+val[j]),dp[i-1][voc-cost[j]]+val[j]);
}
}
}
}
if(dp[k][m]<0)
printf("Impossible\n");
else
printf("%d\n",dp[k][m]);
}
return 0;
}