acdream A - A Math game

本文介绍了一种通过深度优先搜索解决特定数学游戏的算法。游戏中玩家需从一组数中挑选若干数,使其总和等于给定的目标值。文章提供了一个示例程序,使用递归实现的深度优先搜索来判断是否存在一种选择方案使总和达到目标值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >




A - 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.
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,每个数字根据选与不选深搜,当当前和大于H或当前和加上剩余和小于H直接跳出。




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

int n;
long long m;
long long num[100];
long long sum[100];
bool f;
void dfs(int x,long long s)
{
 if (s==m){
  f=true;return;
 }
 if (f) return;
 if (s>m||x==n) return;
 if (sum[n-1]-sum[x]+s+num[x]<m)
  return;
 dfs(x+1,s+num[x]);
 dfs(x+1,s);
}
int main()
{
 int i,j;
 while (scanf("%d%lld",&n,&m)!=EOF)
 {
  for (i=0;i<n;i++)
   scanf("%lld",&num[i]);
  memset(sum,0,sizeof(sum));
  sum[0]=num[0];
  for (i=1;i<n;i++)
   sum[i]=sum[i-1]+num[i];
  f=false;
  dfs(0,0);
  if (!f) printf("No\n");
  else printf("Yes\n");
 }
 
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值