A Math game
Time Limit: 2000/1000MS (Java/Others)
Memory Limit: 256000/128000KB (Java/Others)
Problem Description
Recently, Losanto find an interesting Math game. The rule is simple: Tell you a number
H, and you can choose some numbers from a set {a[1],a[2],......,a[n]}.If the sum of the number you choose is
H, then you win. Losanto just want to know whether he can win the game.
Input
There are several cases.
In each case, there are two numbers in the first line n (the size of the set) and H. The second line has n numbers {a[1],a[2],......,a[n]}. 0<n<=40, 0<=H<10^9, 0<=a[i]<10^9,All the numbers are integers.
In each case, there are two numbers in the first line n (the size of the set) and H. The second line has n numbers {a[1],a[2],......,a[n]}. 0<n<=40, 0<=H<10^9, 0<=a[i]<10^9,All the numbers are integers.
Output
If Losanto could win the game, output "Yes" in a line. Else output "No" in a line.
Sample Input
10 87 2 3 4 5 7 9 10 11 12 13 10 38 2 3 4 5 7 9 10 11 12 13
Sample Output
No Yes
简单的dfs,从大到小dfs即可。
AC代码:
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
#include "queue"
using namespace std;
const int MAXN = 45;
int n, h, a[MAXN], sum[MAXN];
bool flag;
void dfs(int n, int s)
{
if(flag) return;
if(s > sum[n]) return;
if(sum[n] == s || s == 0) {
flag = true;
return;
}
for(int i = n; i >= 1; --i)
if(s >= a[i]) dfs(i - 1, s - a[i]);
}
int main(int argc, char const *argv[])
{
while(scanf("%d%d", &n, &h) != EOF) {
memset(sum, 0, sizeof(sum));
flag = false;
for(int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
sum[i] = sum[i - 1] + a[i];
}
dfs(n, h);
if(flag) printf("Yes\n");
else printf("No\n");
}
return 0;
}
本文介绍了一个名为AMathgame的编程题目,该题目要求玩家从一组数字中选择若干数,使得这些数的总和等于给定的目标数H。文章提供了一种深度优先搜索(DFS)算法解决方案,并给出了完整的AC代码示例。
8万+

被折叠的 条评论
为什么被折叠?



