hdu3033 I love sneakers!【分组背包】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/blue_kid/article/details/80297925


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 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.


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


这个题是分组背包,不同的是每个分组内的物品至少选一个,而不是最多一个。dp[i][j]表示前i组背包容量为j时的最大价值,转移方程:dp[i][j]=max(dp[i][j], dp[i-1][j-item.c]+item.w, dp[i][j-item.c]+item.w)

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e4+5;
struct node{
    int c,w;
    bool operator<(const node&x)const{
        if(c==x.c) return w>x.w;
        return c<x.c;
int dp[12][maxn];
bool vis[12];
int main()
    int n,m,k;
        for(int i=1;i<=10;i++) v[i].clear();
        for(int i=1;i<=n;i++){
            int a,b,c;
        memset(dp,-0x3f,sizeof dp);
        for(int i=0;i<maxn;i++) dp[0][i]=0;//这个初始化非常关键
        for(int i=1;i<=k;i++){
            for(auto it:v[i]){
                for(int j=m;j>=it.c;j--){
        if(dp[k][m]<0) cout<<"Impossible"<<endl;
        else cout<<dp[k][m]<<endl;
    return 0;