来源:http://poj.org/problem?id=1276
题意:就是有一些一定数量和一定面值的钱,还有一个总钱数,让你在所给的纸币中选出一定数目的钱,使这些钱的和小于等于总钱数,并且使这个和尽可能的大。
思路:将总钱数看作是背包的体积,将钱币的面值看作是物体的体积,物体的价值和体积相等。即转化为多重背包问题,由于数据比较大,所以需要用到二进制优化。
代码:
#include <iostream> #include <cstdio> #include <string.h> using namespace std; #define CLR(arr,val) memset(arr,val,sizeof(arr)) struct cash{ int num,val,weight; }cc[15]; int totalweight,dp[100010]; int max(int a,int b){ return a>b?a:b; } void full_bag(int x){ int k = 1; while(k < cc[x].num){ for(int j = k*cc[x].weight;j <= totalweight;++j){ dp[j] = max(dp[j],dp[j - k*cc[x].weight] + k*cc[x].val); } cc[x].num = cc[x].num - k; k = k*2; } for(int j = cc[x].num * cc[x].weight;j <= totalweight;++j) dp[j] = max(dp[j],dp[j - cc[x].num * cc[x].weight] + cc[x].num * cc[x].val); } void one_zero_bag(int x){ int k = 1; while(k < cc[x].num){ for(int j = totalweight;j >= k*cc[x].weight;--j) dp[j] = max(dp[j],dp[j - k*cc[x].weight] + k*cc[x].val); cc[x].num = cc[x].num - k; k = k*2; } for(int j = totalweight;j >= cc[x].num * cc[x].weight;--j) dp[j] = max(dp[j],dp[j - cc[x].num * cc[x].weight] + cc[x].num*cc[x].val); } int main(){ //freopen("1.txt","r",stdin); while(scanf("%d",&totalweight) != EOF){ int n; scanf("%d",&n); for(int i = 0;i < n;++i){ scanf("%d%d",&cc[i].num,&cc[i].val); cc[i].weight = cc[i].val; } CLR(dp,0); for(int i = 0;i < n;++i){ if(cc[i].num * cc[i].weight >= totalweight){ full_bag(i); } else one_zero_bag(i); } printf("%d\n",dp[totalweight]); } return 0; }