POJ 1742 Coins

来源:互联网 发布:淘宝代购华歌尔真假 编辑:程序博客网 时间:2024/06/07 16:58

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

http://poj.org/problem?id=1742


单调队列优化多重背包,由于该题是个多重背包可行性问题,所以只需维护队列的和即可,注意当c[i]=1和c[i]*w[i]>=m时当作01背包和完全背包来做,不然会超时。

#include <cstdio>#include <algorithm>#include <queue>#include <cstring>#define MAXN 105using namespace std;int n,m,c[MAXN],v[MAXN],f[100005],l,r,q[100005];int main(){    while(scanf("%d%d",&n,&m) && n+m)    {        memset(f,0,sizeof(f));        f[0]=1;        for(int i=1;i<=n;i++)            scanf("%d",&v[i]);        for(int i=1;i<=n;i++)            scanf("%d",&c[i]);        for(int k=1;k<=n;k++)        {            if(c[k]==1)            {                for(int i=m;i>=v[k];i--)                    if(f[i-v[k]])                        f[i]=1;            }            else if(c[k]*v[k]>=m)            {                for(int i=v[k];i<=m;i++)                    if(f[i-v[k]])                        f[i]=1;            }            else            {                for(int i=0;i<v[k];i++)                {                    int sum=0,l=1,r=0;                    for(int j=i;j<=m;j+=v[k])                    {                        while(l<=r&&r-l+1>c[k])                            sum-=q[l++];                        sum+=f[j];                        q[++r]=f[j];                        if(sum>0&&!f[j]) f[j]=1;                    }                }            }        }        int ans=0;        for(int i=1;i<=m;i++)            if(f[i])                 ans++;        printf("%d\n",ans);    }}

一些关于单调队列优化多重背包的讲解

http://blog.csdn.net/power721/article/details/5802325
http://imgsrc.baidu.com/forum/pic/item/82ced1628535e5dd6643bfad7ec6a7efce1b6265.jpg
http://www.cnblogs.com/xinsheng/archive/2013/12/04/3458362.html

0 0
原创粉丝点击