A - A Math game
Problem Description
Input
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
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");
}
}