Reprint Address: http://m.blog.csdn.net/blog/u010489766/9229011
Title Link: http://poj.org/problem?id=1276
Test instructions: There are a total of n denominations of coins in the machine, each NI Zhang, to ask the machine to spit less than or equal to the maximum value of the required coins to resolve 1: The problem of Daniel have used multiple backpacks, but I have a classmate to come up with a particularly simple and effective method for this problem. (I think it's not necessary to use the backpack, because the range of n is only 10, too small). The way to do this is to walk through the money to see how many denominations the money can make, and then enumerate down from cash. Because at most only 10*100000 1 million of the amount of data.
The algorithm is enumeration, see 0~cash money is not able to, to is 1, otherwise for 0#include<stdio.h> #include <string.h>int cash,n,n[20],d[20],dp[ 100100];int Main () {while (scanf ("%d", &cash)! = EOF) {memset (n,0,sizeof (n)); memset (d,0,sizeof (d)); Memset (dp,0, sizeof (DP)), int count = 0;dp[0] = 1;scanf ("%d", &n), for (int i = 1; I <= N; i++) scanf ("%d%d", &n[i],&d[i]); fo R (int i = 1; I <= N; i++) {for (int k = cash; k >= 0; k--)//n has a smaller range, so direct enumeration {if (dp[k] = 1) {for (int j = 1; J <= N[i] ; J + +) {if (K+j*d[i] <= cash)//Not added may exceed the range of the array dp[k+j*d[i]] = 1;//here can be directly equal to 1, because the update k above, K or below is the last 1}}}}for (int i = cash; I & gt;= 0; I--) if (dp[i] = = 1) {printf ("%d\n", I); break;}} return 0;}
Resolution 2: Multi-pack, the number of each kind of money according to the binary separate, for example, 13 is divided into 1,2,4,6, (the reason that according to the binary is because of this, less than 13 any number can be composed of 1,2,4,6), and then follow the 01 backpack.
#include <stdio.h> #include <string.h>int cash,n,v[10100],dp[101000];//array to open large enough int main () {while (scanf (" %d ", &cash)! = EOF) {memset (dp,0,sizeof (DP)); memset (V,0,sizeof (v)); scanf ("%d ", &n); int cnt = 0;for (int i = 1; i <= N; i + +) {int a,b,t = 1;scanf ("%d%d", &b,&a), if (b! = 0) {while (T < b)//Here is B separated by binary {b = b-t;v[cnt++] = A * t;t *= 2 ;} v[cnt++] = b*a;}} if (n = = 0 | | cash = = 0) {printf ("0\n"); continue;} Dp[0] = 1;for (int i = 0; i < cnt; i + +) for (int j = cash; J >= V[i]; J-) dp[j-v[i]] = = 1?dp[j] = 1:0;for (int i = Cash I >= 0;i--) {if (dp[i] = = 1) {printf ("%d\n", I); break;}}} return 0;}
"Reprint" POJ 1276 Cash Machine "chip number Problem" "enumeration idea or multi-pack solution"