找出一个数组中能否凑成一个给定的值。
就是相当于找零问题。使用动态规划法了。
原题:
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;
}