SuperSale
There is a SuperSale in a SuperHiperMarket. Every person can take only one object of each kind, i.e. one TV, one carrot, but for extra low price. We are going with a whole family to that SuperHiperMarket. Every person can take as many objects, as he/she can carry out from the SuperSale. We have given list of objects with prices and their weight. We also know, what is the maximum weight that every person can stand. What is the maximal value of objects we can buy at SuperSale?
Input Specification
The input consists of T test cases. The number of them (1<=T<=1000) is given on the first line of the input file.
Each test case begins with a line containing a single integer number N that indicates the number of objects (1 <= N <= 1000). Then follows Nlines, each containing two integers: P and W. The first integer (1<=P<=100) corresponds to the price of object. The second integer (1<=W<=30) corresponds to the weight of object. Next line contains one integer (1<=G<=100) it’s the number of people in our group. Next G lines contains maximal weight (1<=MW<=30) that can stand this i-th person from our family (1<=i<=G).
Output Specification
For every test case your program has to determine one integer. Print out the maximal value of goods which we can buy with that family.
Sample Input
2
3
72 17
44 23
31 24
1
26
6
64 26
85 22
52 4
99 18
39 13
54 9
4
23
20
20
26
Output for the Sample Input
72
514
比较典型的背包问题0-1(解释)
关键:
c[i][j]代表一直放入到第i个物品(当前开始放到第i个)时还剩j的容量时的最优解
当j小于第i个重量时。。放不下于是c[i][j]=c[i-1][j]
否则有两种选择:放OR不放;
得到c[i][j] = max(c[i-1][j],c[i-1][j-ob[i].w]+ob[i].p);
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct object
{
int p;
int w;
}ob[1100];
int person[110];
int n;
int c[1100][40];//c[i][j]代表一直放入到第i个物品(当前开始放到第i个)时还剩j的容量时的最优解
int dp(int max_w)
{
for(int i = 1;i<=n;++i)
for(int j = 1;j<=max_w;++j)
{
if(j<ob[i].w)
c[i][j] = c[i-1][j];
else
c[i][j] = max(c[i-1][j],c[i-1][j-ob[i].w]+ob[i].p);
}
return c[n][max_w];
}
int main()
{
int T;
scanf("%d",&T);
for(int i = 0;i<T;++i)
{
memset(c,0,sizeof(c));
int g;
scanf("%d",&n);
for(int j = 1;j<=n;++j)
scanf("%d%d",&ob[j].p,&ob[j].w);
scanf("%d",&g);
for(int j = 1;j<=g;++j)
scanf("%d",&person[j]);
int sum = 0;
for(int j = 1;j<=g;++j)
{
//dp(person[j]);
sum += dp(person[j]);//c[n][person[j]];
}
printf("%d\n",sum);
}
return 0;
}