Topic website:http://poj.org/problem?id=1276
Ideas:
It is obviously a multi-pack, gross position amount as the capacity of the backpack.
At first, I wanted to take a single amount as an item, and use a three-layer loop to convert it into a 01-pack. T ...
Later, we learned to use binary to process data.
Simple Introduction to binary optimization:? (? ? ??)
Assuming that the quantity is 8, you can think of it as a combination of 1,2,4,1, which means that the combination of these 4 numbers includes all of the 1-8 value cases. What is this for? Convert them to binary and observe again:
1:1
2:10
4:100
1:1
Binary is only 0, 1. So 1,2,4 has been able to make up 1-7 of all cases, but it's not enough to add another 1 to get into 8.
Perhaps someone will ask why not take 8, namely 1,2,4,8. Attention!! all numbers add up to no more than the quantity.
We mainly use these permutations of the number of combinations, the upper limit of 8 will be expanded by us, would be taken to the original value can not be taken.
After decomposing the quantity into a number[i]*value as an item, you can convert it into a 01 backpack ~ See the code for details!
Code:
1#include <cstdio>2#include <cstring>3#include <vector>4#include <cmath>5#include <algorithm>6 using namespacestd;7 intdp[100005];8 inta[ the];9vector<int>v;Ten intMain () { One intCash; A intn,m,x; - while(SCANF ("%d%d", &cash,&n)! =EOF) { -Memset (DP,0,sizeof(DP)); the v.clear (); -dp[0]=1; - for(inti =0; I < n; ++i) { -scanf"%d%d",&m,&x); + for(intj =1; J <= M; j<<=1) {//Binary Optimization -V.push_back (j*x); +m-=J; A } at if(m>0) V.push_back (m*x);//Don't forget the remaining numbers. - } - for(inti =0; I < v.size (); ++i) { - for(intj = Cash; J >=v[i]; --j) { -Dp[j]=max (dp[j-v[i]],dp[j]); - } in } - for(inti = cash; I >=0; --i) { to if(Dp[i]) { +printf"%d\n", i); - Break; the } * } $ }Panax Notoginseng return 0; -}
POJ 1276 Cash Machine (multi-pack binary optimization)