POJ1742--Coins

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-23 19:33   221   0

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

传说中的男人八题之一。。。

多重背包问题,我将二进制优化转换为0-1背包,超时。。

以下是超时代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int dp[100008];
int xinstv[1008],xinstw[1008];
int A[108];int W[108];
bool vis[100008];
inline int max(int a,int b)
{
 return a>b?a:b;
}
int main()
{
 int n,m;
 while(scanf("%d%d",&n,&m)==2&&(n||m))
 {
  memset(vis,0,sizeof(vis));
  memset(dp,0,sizeof(dp));
  int t=0;
  for(int i=1;i<=n;i++)
  {
   scanf("%d",&A[i]);//A[i]是币种
  }
  for(int i=1;i<=n;i++)
  {
   scanf("%d",&W[i]);//这是数量
  }
  for(int i=1;i<=n;i++)
  {
   int temp=1;
   while(W[i]/temp)
   {
    xinstv[t]=temp*A[i];
    xinstw[t++]=temp*A[i];
    W[i]-=temp;
    temp=temp*2;
   }
   xinstv[t]=W[i]*A[i];
   xinstw[t++]=W[i]*A[i];
  }
  int sum=0;
  vis[0]=1;
  for(int i=0;i<t;i++)
  {
   for(int j=m;j>=xinstw[i];j--)
   {
    if(!vis[j]&&vis[j-xinstv[i]])
    {
     sum++;
     vis[j]=1;
    }
   }
  }
  printf("%d\n",sum);
 }
 return 0;
}
以下是AC代码。。
#include<stdio.h>
int use[100005],c[105];
char p[100005];
int main()
{
    int n,m,i,j,s,res;
    p[0]=1;
    while(scanf("%d%d",&n,&m),n||m)
    {
        res=0;
        for(i=1;i<=m;i++) p[i]=0;
        for(i=0;i<n;i++) scanf("%d",&c[i]);
        for(i=0;i<n;i++)
        {
            for(j=0;j<=m;j++) use[j]=0;
            scanf("%d",&s);
            for(j=c[i];j<=m;j++)
            {
                if(!p[j]&&p[j-c[i]]&&use[j-c[i]]<s)//贪心过程
                {
                    use[j]=use[j-c[i]]+1;
                    p[j]=1;
                    res++;
                }
            }
        }
        printf("%d\n",res);
    }
    return 0;
}



分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP