A Math GameTime limit:2000/1000ms (java/others)
Memory limit:256000/128000kb (java/others)Problem descriptionrecently, 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. Inputthere is several cases.
In each case, there is 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 is
integers.Outputif Losanto could win the game, output "Yes" in a line. Else output "No" in a line. Sample Input
10 872 3 4 5 7 9 10 11 12 1310 382 3 4 5 7 9 10 11 12 13
Sample Output
NoYes
SOURCE Nineth session Beijing University Program Design contest
Title Link: http://acdream.info/problem?pid=1726
Topic: part and question
Title Analysis: Positive solution is two +dfs, I practice is DFS with prefix and pruning, 4ms over, estimate or data water,
#include <cstdio> #include <cstring> #define LL long Longll a[45], H, sum[45];int n;bool flag; void DFS (ll num, int pos) { if (num = = h) { flag = true; return; } if (flag | | pos = = n + 1) return; Returns if the current number plus the remaining number and less than H or the current number is greater than H (Sum[n]-sum[pos-1] + num < h | | num > h) return ; DFS (num + a[pos], pos + 1); DFS (num, pos + 1); return;} int main () {while (scanf ("%d%lld", &n, &h)! = EOF) { memset (sum, 0, sizeof (sum)); Flag = false; for (int i = 1; I <= n; i++) { scanf ("%lld", &a[i]); Sum[i] = Sum[i-1] + a[i]; } DFS (0, 1); if (flag) printf ("yes\n"); else printf ("no\n");} }
Acdream 1726 A Math game (partial and problem Dfs pruning)