当前位置: 代码迷 >> 综合 >> POJ-1742 Coins 可行性背包DP 鶸的DP解题报告
  详细解决方案

POJ-1742 Coins 可行性背包DP 鶸的DP解题报告

热度:57   发布时间:2023-12-12 14:15:42.0

题目:

Coins
Time Limit: 3000MS   Memory Limit: 30000K
Total Submissions: 41402   Accepted: 14020

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

题意:给出n种硬币,和每种硬币的数量,求在价值1到价值m之间,这些硬币能凑出来的种类数。

思路:可以先只用第一种硬币,看看能凑出哪些价值。然后在这些凑出的价值的基础上,用第二种硬币,得到用第一种和第二种能凑出的所有价值。直到求出用第一种到第n种得到的价值。

用f[i]表示价值i是否被凑出来了。用use[i]表示在使用当前硬币时,凑出i价值需要用该硬币的数量。

则在使用a[i]价值的硬币时,如果j价值还没有被凑出来,且j-a[i]价值已经被凑出来,凑出j-a[i]时a[i]价值的硬币用量小于该硬币的总数量,那么就可以在j-a[i]价值的基础上用一个a{i]价值的硬币,从而凑出j价值

代码:

#include<cstdio>  
#include<cstdlib>  
#include<cmath>  
#include<cstring>  
#include<iostream>  
#include<algorithm>  
#include<queue>  
#include<map>  
#include<stack> 
#include<set>
#define sd(x) scanf("%d",&x)
#define ss(x) scanf("%s",x)
#define sc(x) scanf("%c",&x)
#define sf(x) scanf("%f",&x)
#define slf(x) scanf("%lf",&x)
#define slld(x) scanf("%lld",&x)
#define me(x,b) memset(x,b,sizeof(x))
#define pd(d) printf("%d\n",d);
#define plld(d) printf("%lld\n",d);
#define eps 1.0E-8
// #define Reast1nPeacetypedef long long ll;using namespace std;const int INF = 0x3f3f3f3f;int a[110];
int c[110];
int n,m;int use[100010];  //使用当前硬币凑成i元时,该硬币的用量 
bool f[100010];   //i是否被凑出来了 int main(){
#ifdef Reast1nPeacefreopen("in.txt", "r", stdin);freopen("out.txt", "w", stdout);
#endifios::sync_with_stdio(false);while(cin>>n>>m){if(n==0 && m==0)	break;for(int i = 1 ; i<=n ; i++){cin>>a[i];}for(int i = 1 ; i<=n ; i++){cin>>c[i];}memset(f,0,sizeof(f));int ans = 0;f[0] = 1;for(int i = 1 ; i<=n ; i++){memset(use,0,sizeof(use));for(int j = a[i] ; j<=m ; j++){if(!f[j] && f[j-a[i]] && use[j-a[i]]+1<=c[i]){  f[j] = 1;use[j] = use[j-a[i]]+1;ans++;}}} cout<<ans<<endl;}return 0;                                                  
}