Coins —— POJ-1742

版权声明:没什么好说的,版权声明呢 https://blog.csdn.net/weixin_43741224/article/details/85287510
Time limit 3000 ms
Memory limit 30000 kB

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

题目分析

这个题已经有很多大佬写出来了,我就简单的分析一下吧。

这个题的目的是求1-m 之间有多少个价值可以用 n 个银币凑齐,所以我们在DP的过程中标记一下这个价值就可以了。

我觉得代码里面写的很详细了,所以就不多说了

代码区

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

const int maxn = 100000 + 10;		//数组要开到10000 ,我也是有点怕内存呀,不过没爆就对了

int v[maxn], w[maxn],dp[maxn];


int main()
{
	int n,m;
	while(cin>>n>>m && n && m)
	{
		//乏味的读取数据
		for(int i = 1; i <= n ; i++)
		{
			cin >> v[i];
		}
		for (int i = 1; i <= n; i++)
		{
			cin >> w[i];
		}

		//进入正片了
		memset(dp, -1, sizeof(dp));		//dp[i] >= 0 表示价值i可以被凑齐,而 dp[i] = -1 ,表示无法凑齐
		//下标表示价值
		dp[0] = 0;				//表示价值为0 的不需要任何银币,所以其值为0

		for(int i = 1 ; i <= n ; i ++)		//从第一种银币开始
		{
			for(int j = 0 ; j <= m ; j ++)	//枚举价值,检验是否某一价值可以利用 第 i 个银币转移而来
			{
				if (dp[j] >= 0)		//这意味着这个价值已经被找到,不需要判断是否可以凑齐
					dp[j] = w[i];	//表示这一状态还剩下可以用于转移的银币数量,不过这是初始设定的,
											//已经凑齐的价值可以通过加上若干个第i中银币找到下一个可以凑齐的价值


				else if (j < v[i] || dp[j-v[i] ]  <= 0)
				{							//前一个条件表示剩余价值不能再加上一个该种银币以实现状态转移
											//后一个条件表示用了这个价值的银币用完了,或者用之前的状态凑不齐,没有根基,转移不起
											//也就是上一个状态不能实现,那么在上一状态的基础上加上银币,不能保证目前状态可以实现。
											//dp[j]的值表示还可以使用第i中银币数,银币数不足的时候自然不能继续转移下去
											//对于这种清空,此时 dp[ j- val[i]]的值为0 ,则转移后dp[j]的值变为-1,表示无法凑成

					dp[j] = -1;				//表示无法实现
				}

				else
				{							//执行到了这一步,满足条件:
											//1:这一价值还没有被确定可以凑齐,dp[j]在复制之前值为-1
											//2:用价值为val[i] 的银币,凑成价值为j的状态是存在的,也就是有路可以继续走下的意思
											//3:此时的j一定可以被凑齐
					dp[j] = dp[j - v[i]] - 1;
				}
			}
		}
		int sum = 0;				//统计可凑齐的价值个数
		for(int i = 1; i <= m ;i ++)		//由题意可知价值0不算在内
		{
			if (dp[i] >= 0)			//dp[i]>=0 意味着价值 i 可以被凑齐
				sum++;
		}
		cout << sum << endl;
		//一组数据结束
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43741224/article/details/85287510