poj 1742coins(优化的多重背包)。。

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

题解:

第一行输入,n,m分别表示n种硬币,m表示总钱数。
第二行输入n个硬币的价值,和n个硬币的数量。
输出这些硬币能表示的所有在m之内的硬币种数。

代码

#include<iostream>
#include<string.h>
using namespace std;
int dp[100005],p[105],c[105];
int num[100005];
int main()
{
    int n,m,i,j,k,cnt;
    while(cin>>n>>m)
    {
        if(n==0&&m==0)
            break;
        for(i=0;i<n;i++)
            cin>>p[i];// 记录硬币的价值 
        for(i=0;i<n;i++)
            cin>>c[i];//记录各硬币的数量 
        for(i=0;i<=m;i++)
            dp[i]=0;//标记数组 (相当于vis)
        dp[0]=1;
        cnt=0;
        //滚动数组 
        for(i=0;i<n;i++)
        {
            for(j=0;j<=m;j++)//记录使用次数
                num[j]=0;
            for(j=p[i];j<=m;j++)
            {
                if(!dp[j]&&dp[j-p[i]]&&num[j-p[i]]<c[i])
                {
                    num[j]=num[j-p[i]]+1;
                    dp[j]=1;
                    cnt++;//记录种数
                }
            }
        }
        cout<<cnt<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lshsgbb2333/article/details/79931243