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
#include<iostream>
using namespace std;
long long int a[50],n,h,s;
int f;
void dfs(long long int m,int k)
{
if(h==m)
{
f=1;
return;
}
if(k>=n||h<m||f==1)
return ;
dfs(m,k+1) ; //表示这个数不加,跳过。
dfs(m+a[k],k+1);//表示加上这个数。
}
int main()
{
int i;
while(cin>>n>>h)
{
f=0;s=0;
for(i=0;i<n;i++)
{
cin>>a[i];
s+=a[i];
}
if(s<h) //加上这个判断,不然回爆掉;
{cout<<"No"<<endl;continue;
}
dfs(0,0);
if(f==1)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
return 0;;
}