codeforces Paying up 题解

本文介绍了一种利用动态规划解决找零问题的方法,并通过一个具体的编程实例展示了如何判断一个数组中的元素是否能组合成给定的目标值。该方法适用于如CodeChef等在线编程挑战赛中的相关题目。

找出一个数组中能否凑成一个给定的值。

就是相当于找零问题。使用动态规划法了。

原题:

http://www.codechef.com/problems/MARCHA1/

Example

Input:
5
3 3
1
1
1
5 11
1
2
4
8
16
5 23
1
2
4
8
16
5 13
1
5
5
10
10
20 132
17
6
4
998
254
137
259
153
154
3
28
19
123
542
857
23
687
35
99
999

Output:
Yes
Yes
Yes
No
Yes

 

#include <string>
#include <algorithm>
#include <stdio.h>
#include <iostream>
using namespace std;

namespace{
	static const int ALL_MON = 1000;
}
int Payingup()
{
	int T = 0, n, m; // n, the number of banknotes in your wallet, and m, the amount of money the muggers asked of you. 
	scanf("%d", &T);
	while (T--)
	{
		scanf("%d %d", &n, &m);
		int *A = new int[n];
		for (int i = 0; i < n; i++)
		{
			scanf("%d", &A[i]);
		}
		if (m > ALL_MON)
		{
			puts("No");
			continue;
		}
		int *B[2];
		B[0] = new int[2*m+2];
		memset(B[0], 0, (2*m+2)*sizeof(int));
		B[1] = B[0] + m+1;
		bool id = 0;
		B[0][0] = B[1][0] = 1;
		for (int i = 0; i < n; i++)
		{
			id = !id;
			for (int j = 1; j <= m; j++)
			{
				if (B[!id][j] || j >= A[i] && B[!id][j - A[i]]) 
					B[id][j] = 1;
			}
		}
		if (B[id][m]) puts("Yes");
		else puts("No");
		delete [] A;
		delete [] B[0];
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值