10 87 2 3 4 5 7 9 10 11 12 13 10 38 2 3 4 5 7 9 10 11 12 13
No Yes
#include <cstdio> #include <cstring> #define ll long long ll 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; //若当前数字加剩下的数字和小于h或者当前数字大于h则返回 //不加妥T if(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 (部分和问题 DFS剪枝)
原文地址:http://blog.csdn.net/tc_to_top/article/details/45653067