当前位置: 首页 > 图灵资讯 > 技术篇> POJ 1742 Coins (背包)

POJ 1742 Coins (背包)

来源:图灵教育
时间:2023-05-15 09:27:55

大体题意:

告诉你有n 种植硬币,告诉你每种硬币的价值和数量,问你1~的价值m 能凑出多少种?

思路:

类似背包:

令dp[i] = 1 表示价值为i 可以凑出来, 等于0 说明凑不出来。

然后直接看每个硬币DP[j - a[i]]是否为1 可以,如果是1,可以转移到dp[j]

还有另一个条件 数量问题:

我们直接打开cnt 数组, cnt[j]表示凑出值为j ,需要目前硬币种类的数量。转移时 当数量合适时,可以转移

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;int dp[(int)1e5+7];int cnt[(int)1e5+7];int a[107];int num[107];int main(){    int n,m;    while(~scanf("%d %d",&n, &m) && (m || n)){        for (int i = 1; i <= n; ++i) scanf("%d",a+i);        for (int i = 1; i <= n; ++i) scanf("%d",num+i);        memset(dp,0,sizeof dp);        dp[0] = 1;        int ans = 0;        for (int i = 1; i <= n; ++i){            memset(cnt,0,sizeof cnt);            for (int j = 0; j <= m; ++j){                if (!dp[j]){                    if (j >= a[i] && cnt[j-a[i] ] < num[i] && dp[j-a[i] ]){                        dp[j] = dp[j-a[i] ];                        cnt[j] = cnt[j-a[i] ] + 1;                        ++ans;                    }                }            }        }        printf("%d\n",ans);    }    return 0;}

Coins

Description

People in Silverland use coins.They have coins of value A1,A2,A3...An Silverland dollar.One day Tony opened his money-box and found there were some coins.He decided to buy a very nice watch in a nearby shop. He wanted to pay the exact price(without change) and he known the price would not more than m.But he didn't know the exact price of the watch. You are to write a program which reads n,m,A1,A2,A3...An and C1,C2,C3...Cn corresponding to the number of Tony's coins of value A1,A2,A3...An then calculate how many prices(form 1 to m) Tony can pay use these coins.

Input

The input contains several test cases. The first line of each test case contains two integers n(1<=n<=100),m(m<=100000).The second line contains 2n integers, denoting A1,A2,A3...An,C1,C2,C3...Cn (1<=Ai<=100000,1<=Ci<=1000). The last test case is followed by two zeros.

Output

For each test case output the answer on a single line.

Sample Input

3 101 2 4 2 1 12 51 4 2 10 0

Sample Output

84

Source

LouTiancheng@POJ

Time Limit:3000MS

Memory Limit:30000K

Total Submissions:36299

Accepted:12308

[Submit] [Go Back] [Status] [Discuss]