Title: Coins
Links: http://poj.org/problem?id=1742
Test Instructions: give you n kinds of coins, each of the value of AI, each of the number of CI, ask you to use these n coins can be made into 1-m in the number of values, output quantity. (n<=100,m<=10 million, 1<=ai<=10, 1<=ci<=1000)
train of thought: If the time complexity is n*m*ci with the ordinary knapsack algorithm, will reach O (10 billion), will definitely time out, now we define: Dp[i][j]: The first I kind of coin, composition J, the first I kind of coin still how many, if cannot compose J is set to negative. So, dp[i][j]=dp[i-1][j]>=0? C[i]:d p[i][j-a[i]]-1. This means: If the former I have been able to directly form J, then I am definitely all left, if not, I will see the composition of j-a[i] I used how much, now more than one a[i], so the remaining quantity minus 1. Of course, two-dimensional DP arrays can be compressed into one dimension.
1#include <stdio.h>2#include <string.h>3 intn,m;4 inta[ the];5 intc[ the];6 intdp[100010];7 intMain ()8 {9 while(SCANF ("%d%d", &n,&m)! =EOF)Ten { One if(n==0&&m==0) Break; A for(intI=0; i<n;i++) - { -scanf"%d",&a[i]); the } - intx; - for(intI=0; i<n;i++) - { +scanf"%d",&x); -c[i]=x; + } Amemset (dp,-1,sizeof(DP)); at for(intI=0; i<n;i++) - { -dp[0]=C[i]; - for(intj=0; j<a[i];j++) -dp[j]=dp[j]<0?-1: C[i]; - for(intj=a[i];j<=m;j++) in { - if(dp[j]>=0) dp[j]=C[i]; to Elsedp[j]=dp[j-a[i]]-1; + } - } the intco=0; * for(intI=1; i<=m;i++) $ if(dp[i]>=0) co++;Panax Notoginsengprintf"%d\n", CO); - } the return 0; +}
POJ 1742 Coins