See also 01 backpack time limit: ms | Memory limit:65535 KB Difficulty:3
-
Describe
-
there are n items with a weight and value of WI and VI, from which items with a total weight of not more than W are selected, and the maximum value of the sum of the items in all selection options is obtained. 1 <= N <=100 1 <= wi <= 10^7 1 <= vi <= 1 <= W <= 10^9
-
Input
-
Multiple sets of test data. Each set of test data is entered in the first row, N and W, followed by n lines, each line entered two numbers, representing the first item of WI and VI.
-
Output
-
Meet the maximum value of test instructions, one row per group of test data.
-
Sample input
-
4 52 31 23 42 2
-
Sample output
-
7
Ideas:
-
01 backpack new ideas, when the quality is too large, will appear too large memory, change the idea, because 100*100 is the total value of the maximum value of 10000, so the value of the backpack into the V of the minimum quality, this into a full backpack, So make the backpack initialized to Max;
-
code: #include <stdio.h>
struct goods{
int w,v;
}goods[110];
#define MAX 1<<30
int bag[10010];
Int main () {
int w,n,v,value;
while (~scanf ("%d%d", &n,&w)) {v=0;
//printf ("%d\n", MAX);
for (int i=0;i<n;++i) scanf ("%d%d", &goods[i].w,&goods[i].v), V+=GOODS[I].V;
for (int i=1;i<=v;++i) Bag[i]=max;
bag[0]=0;
for (int i=0;i<n;++i) {
for (int j=v;j>=goods[i].v;j--) {
bag[j] =bag[j-goods[i].v]+goods[i].w<bag[j]?bag[j-goods[i].v]+goods[i].w:bag[j];
}
}
for (int i=0;i<=v;++i) Value=bag[i]<=w?i: Value
printf ("%d\n", value);
}
return 0;
}
See also 01 backpack