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
Source
第九届北京化工大学程序设计竞赛
题目链接:http://acdream.info/problem?pid=1726
题目大意:取一组数字中的任意一些数,看能否组成目标数。
解题思路:深搜,很简单能想到,避免T需要做小小的优化。即递减排序以及从后往前记录数字和。如果当前值加上后面所有未使用的数字还小于目标值,说明已无解,不需要再往下递归。
代码如下:
题目链接:http://acdream.info/problem?pid=1726
题目大意:取一组数字中的任意一些数,看能否组成目标数。
解题思路:深搜,很简单能想到,避免T需要做小小的优化。即递减排序以及从后往前记录数字和。如果当前值加上后面所有未使用的数字还小于目标值,说明已无解,不需要再往下递归。
代码如下:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define ll long long
using namespace std;
ll a[45],vis[45],sum[45];
int n,p;
ll k;
int cmp(ll u,ll v)
{
return u>v;
}
void dfs(int s,ll cur)
{
if(k==cur||p)
{
p=1;
return ;
}
if(s>=n)
return;
for(int i=s;i<n;i++)
{
if(vis[i])
continue;
if(cur+sum[i]<k) //如果当前值加上后面所有未使用的数字还小于目标值,说明已无解,不需要再往下递归
return;
if(cur+a[i]<=k)
{
vis[i]=1;
dfs(i+1,cur+a[i]);
if(p)
return;
vis[i]=0;
}
}
}
int main(void)
{
while(scanf("%d%I64d",&n,&k)!=EOF)
{
p=0;
memset(vis,0,sizeof(vis));
memset(sum,0,sizeof(sum));
for(int i=0;i<n;i++)
scanf("%I64d",&a[i]);
sort(a,a+n,cmp);
for(int i=n-1;i>=0;i--)
sum[i]=sum[i+1]+a[i]; //从后往前记录数字和
dfs(0,0);
if(p)
printf("Yes\n");
else
printf("No\n");
}
}