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 31 4 62 5 73 4 991 55 772 44 66
Sample Output
255
題意就是說有一個人有錢m他想要買些,這些鞋子有k種商標,每種商標的產品的價格為b,價值為c問如何買能使得獲得的價值是最大的,注意這邊是每種商標的商品至少買一件,和背包九講裡面分組背包有所不同,詳情可以參考背包九講,下面給出解釋和代碼:
/*目前狀態的來源有二:A、當前品牌數目的前提之下獲得的最大價值;B、在比當前數目小的基礎之上放一個另外品牌的商品所獲得的最大價值;所以我們就很容易就設計出狀態轉移方程:f[j][v]= max(f[j][v], f[j][v-cost]+value); f[j][v]= max(f[j][v], f[j-1][v-cost]+value); f[j][v]表示為前j種商品放入體積為v獲得的最大價值*/#include<stdio.h>#include<string.h>#include<stdlib.h>#define max(a,b) a>b?a:bint dp[15][10010];int main(){int n,m,i,j,k,p,q,o,cnt[15],v[15][110],w[15][110];while(scanf("%d%d%d",&n,&m,&k)!=EOF){memset(cnt,0,sizeof(cnt));for(i=0;i<n;i++){scanf("%d%d%d",&p,&q,&o);v[p][cnt[p]]=o;w[p][cnt[p]++]=q;}//初始化很奇妙,很有技巧memset(dp,-1,sizeof(dp));//由於商品的價值可能是0,所以初始化不能為0for(i=0;i<=m;i++)//表示的意思可以好好的理解 dp[0][i]=0;for(i=1;i<=k;i++){for(j=0;j<cnt[i];j++)//2 3 迴圈對調就成了每組最多選一件了 現在的迴圈是每組至少選一件 很神奇吧{for(p=m;p>=w[i][j];p--){//如果分開寫下面兩條語句語句不能換,一旦換了當w[i][j]==0時會加2次dp[i][p]=max(dp[i][p],dp[i][p-w[i][j]]+v[i][j]);dp[i][p]=max(dp[i][p],dp[i-1][p-w[i][j]]+v[i][j]);/*或者改成dp[i][p]=max(dp[i][p],max(dp[i][p-w[i][j]]+v[i][j],dp[i-1][p-w[i][j]]+v[i][j]))*/}}}if(dp[k][m]==-1)printf("Impossible\n");elseprintf("%d\n",dp[k][m]);}return 0;}