POJ 1276
这是一道简单的多重背包问题,思路就是将多重背包转换为01背包,这道题由于我的函数 mkpackage()没有写对,导致在这道题上卡了很久。
这种使用二进制思想划分物品的思路还需要理解,这一点非常重要。
#include<stdio.h> #include<string.h> #define MAX_CASH_KIND 100 #define MAX_DP_SPACE 100005 #define MAX_STACK_SPACE 100001 int get_max(int ,int ),top=0,stk[MAX_STACK_SPACE]; void mkpackage(int,int,int); int main() { int cashReq,totalAmount,cashKind[MAX_CASH_KIND],cashAmount[MAX_CASH_KIND],dp[MAX_DP_SPACE]; while(scanf("%d%d",&cashReq,&totalAmount)!=EOF) { int i,j; for(i=1;i<=totalAmount;i++) { scanf("%d%d",&cashAmount[i],&cashKind[i]); } if(cashReq==0||totalAmount==0) { printf("0\n"); continue; } top=0; for(i=1;i<=totalAmount;i++) { if(cashKind[i]<=cashReq) { mkpackage(cashKind[i],cashAmount[i],cashReq); } } memset(dp,0,sizeof(dp)); for(i=0;i<top;i++) { for(j=cashReq;j>=stk[i];j--) { dp[j]=get_max( dp[j],dp[j-stk[i]]+stk[i]); } } printf("%d\n",dp[cashReq]); } return 0; } int get_max(int x,int y) { return x>=y?x:y; } void mkpackage(int x,int amount,int cashReq) { int k=1; while(k<amount) { stk[top]=k*x; top++; amount-=k; k=k*2; } stk[top]=amount*x;//以前忘记加 top++;//************这两行代码 }