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.
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.
5 10000 3 1 4 6 2 5 7 3 4 99 1 55 77 2 44 66
分析:分组背包的典型模型,分组背包就是将0-1背包的种类换成组数,然后进行每个组内的选取,每个组最多可以选一个或者不选,基本模板是一个三重循环,
for(i=1;i<=N;i++)//组数
for(j=M;j>=0;j--)//体积
for(k=1;k<=j;k++)//每个组的物品
f[j]=max(f[j],f[j-k]+A[i][k]);
而这个题则是每个组至少选择一个,还有一个就是,所有鞋的价格为0的时候,这个时候是无法辨别能否满足要求,所以我们要把初始的值设置一个不同的值,作为标记,看代码:
import java.util.*; public class Main { static Scanner in = new Scanner(System.in); static int[][] dp = new int[105][10005]; static int[] no = new int[1005]; static int[] va = new int[1005]; static int[] we = new int[1005]; static int max(int a,int b,int c) { return a>b?(a>c?a:c):(b>c?b:c); } public static void main(String[] args) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); for(int i = 0;i < n;i++) { no[i] = in.nextInt(); we[i] = in.nextInt(); va[i] = in.nextInt(); } int i,j,p; for(i=0;i<=k;i++) { for(j=0;j<=m;j++){ if(i==0) dp[i][j]=0; //运动鞋价格可能全部为零 else dp[i][j]=-1; } } for( i = 1;i <= k;i++) for(j = 0;j < n;j++) if(no[j] == i)//第i种鞋 for(p = m;p >= we[j];p--) //不选当前这一种,选择当前这一种并且不是第一个,选择当前这一种并且是第一个 dp[i][p] = max(dp[i][p],dp[i][p-we[j]]+va[j],dp[i-1][p-we[j]]+va[j]); if(dp[k][m]<0) System.out.println("Impossible"); else System.out.println(dp[k][m]); } }