hdu 2844 Coins(多重背包)

来源:互联网 发布:群晖 路由器开放端口 编辑:程序博客网 时间:2024/06/01 08:00

题目大意:

        一个人有n种硬币,面值为A1-An,每种硬币的个数为C1-Cn,问可以组成m元以下的不同价值的总数。

解题思路:

        中规中矩的多重背包问题。

代码:

#include <iostream>#include <stdio.h>#include <cstring>using namespace std;int n,m;int a[105],c[105],newA[1050],f[100005];int ans;int main(){    while(true){        scanf("%d%d",&n,&m);        if(n == 0 && m == 0) break;        for(int i = 0; i < n; i ++){            scanf("%d",&a[i]);        }        for(int i = 0; i < n; i ++){            scanf("%d",&c[i]);        }        int pos = 0;        for(int i = 0; i < n; i ++){            int temp = 1;            while(c[i] > temp){                if(a[i] * temp > m) break;//如果当前组成的面额大于m则停止,因为不可能被用到,直接舍弃                newA[pos++] = a[i] * temp;                c[i] -= temp;                temp *= 2;            }            if(c[i] != 0 && a[i] * c[i] <= m){                newA[pos++] = a[i] * c[i];            }        }        n = pos;        memset(f,false,sizeof(f));        f[0] = true;        for(int i = 0; i < n; i ++){            for(int j = m; j >= newA[i]; j --){                f[j] = f[j] || f[j - newA[i]];            }        }        ans = 0;        for(int j = 1; j <= m; j ++){            if(f[j]) ans ++;        }        printf("%d\n",ans);    }    return 0;}


0 0