POJ 1742 Coins (背包)

    xiaoxiao2021-03-25  161

    大体题意:

    告诉你有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 Time Limit: 3000MS Memory Limit: 30000KTotal Submissions: 36299 Accepted: 12308

    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 10 1 2 4 2 1 1 2 5 1 4 2 1 0 0

    Sample Output

    8 4

    Source

    LouTiancheng@POJ

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

    转载请注明原文地址: https://ju.6miu.com/read-5794.html

    最新回复(0)