POJ 1742 Coins 【多重揹包】【可行性問題】

POJ 1742 Coins 

大致意思:

給出硬幣面額及每種硬幣的個數,求從1到m能湊出面額的個數。 

 

Input

多組數據,每組數據前兩個數字爲n,m。n表示硬幣種類數,m爲最大面額,之後前n個數爲每種硬幣的面額,後n個數爲相應每種硬幣的個數。 (n<=100,m<=100000,面額<=100000,每種個數<=1000)

Output

面額數

 

 

Sample Input

3 10
1 2 4 2 1 1
2 5
1 4 2 1
0 0

Sample Output

8
4

---------------------------------------------------

第一組數據,可以組成面額爲1.2.3.4.5.6.7.8的·,都在m=10之內,共8種

第二組數據,可以組成面額爲1.2.4.5.6的·,但是6不在m=5之內,滿足的共4種

 

 

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define max_n 100010
using namespace std; 
int a[max_n], b[max_n], dp[max_n], vis[max_n];

int main() {
    int n, m, k, ans;
    while(scanf("%d %d", &n, &m) && (n + m)) {
        for(int i = 0; i < n; i++)
            scanf("%d", &a[i]);
        for(int i = 0; i < n; i++)
            scanf("%d", &b[i]);
        memset(vis, 0, sizeof(vis));
        ans = 0,vis[0] = 1;
        for(int i = 0; i < n; i++) {
            memset(dp, 0, sizeof(dp));
            for(int j = a[i]; j <= m; j++) {
                if(!vis[j] && vis[j - a[i]] && dp[j - a[i]] + 1 <= b[i]) {
                    vis[j] = 1;
                    dp[j] = dp[j - a[i]] + 1; //表示a[i]的使用次數
                    ans++;
                }
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章