1 2 1 4 3 2 4 5
NO YES YESHintFor the Case 1:Put the 4 weight alone For the Case 2:Put the 4 weight and 1 weight on both side
分析:动态规划,对于前X个砝码,若能组合出质量为K的物品,则需要前X-1个砝码能组合出K-W[X]或K+W[X]或K的重量。
最后直接访问DP数组即可。
CODE:
//************************************************************************// //*Author : Handsome How *// //************************************************************************// //#pragma comment(linker, "/STA CK:1024000000,1024000000") #pragma warning(disable:4996) #include <vector> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <algorithm> #include <sstream> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <cstring> #include <ctime> #include <cassert> #if defined(_MSC_VER) || __cplusplus > 199711L #define aut(r,v) auto r = (v) #else #define aut(r,v) __typeof(v) r = (v) #endif #define each(it,o) for(aut(it, (o).begin()); it != (o).end(); ++ it) #define fur(i,a,b) for(int i=(a);i<=(b);i++) #define furr(i,a,b) for(int i=(a);i>=(b);i--) #define cl(a) memset((a),0,sizeof(a)) using namespace std; typedef long long LL; //---------------------------------------------------- bool dp[25][2500]; int a[30]; int main() { //freopen("E:\\data.in", "r", stdin); ios :: sync_with_stdio(false); int T; scanf("%d", &T); while (T--) { int n; scanf("%d", &n); fur(i, 1, n)scanf("%d", &a[i]); cl(dp); dp[0][0] = true; fur(i, 1, n)fur(j, 0, 2000) { if (j >= a[i]) if (dp[i - 1][j - a[i]]) dp[i][j] = 1; if (j + a[i] <= 2000) if (dp[i - 1][j + a[i]]) dp[i][j] = 1; if (dp[i - 1][j]) dp[i][j] = 1; } int q; scanf("%d", &q); while (q--) { int t; scanf("%d", &t); if (t > 2000) { printf("NO\n"); continue; } if (dp[n][t]) { printf("YES\n"); continue; } printf("NO\n"); } } return 0; }