Jam's balance
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1343 Accepted Submission(s): 600
Problem Description
Jim has a balance and N weights.
(1≤N≤20)
The balance can only tell whether things on different side are the same weight.
Weights can be put on left side or right side arbitrarily.
Please tell whether the balance can measure an object of weight M.
The balance can only tell whether things on different side are the same weight.
Weights can be put on left side or right side arbitrarily.
Please tell whether the balance can measure an object of weight M.
Input
The first line is a integer
T(1≤T≤5),
means T test cases.
For each test case :
The first line is N, means the number of weights.
The second line are N number, i'th number wi(1≤wi≤100) means the i'th weight's weight is wi.
The third line is a number M. M is the weight of the object being measured.
For each test case :
The first line is N, means the number of weights.
The second line are N number, i'th number wi(1≤wi≤100) means the i'th weight's weight is wi.
The third line is a number M. M is the weight of the object being measured.
Output
You should output the "YES"or"NO".
Sample Input
1 2 1 4 3 2 4 5
Sample Output
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 【题意】裸的01背包,直接上代码了。 【AC代码】// //Created by just_sort 2016/9/9 20:37 //Copyright (c) 2016 just_sort.All Rights Reserved // #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int maxn = 25; int dp[maxn][maxn*200]; int a[maxn]; int main() { int T; scanf("%d",&T); while(T--) { int sum = 0; int n; scanf("%d",&n); for(int i=1; i<=n; i++) scanf("%d",&a[i]); for(int i=1; i<=n; i++) sum += a[i]; memset(dp,false,sizeof(dp)); dp[0][sum]=true; for(int i=1; i<=n; i++){ for(int j=0; j<=sum*2; j++){ if(dp[i-1][j]){ dp[i][j] = true; dp[i][j+a[i]] = true; if(j>=a[i]) dp[i][j-a[i]]=true; } } } int q; scanf("%d",&q); while(q--) { int x; scanf("%d",&x); if(x>sum){ printf("NO\n"); } else{ if(dp[n][x+sum]) printf("YES\n"); else printf("NO\n"); } } } return 0; }
本文介绍了一个经典的01背包问题的应用实例——通过不同重量的砝码来判断能否准确测量特定重量的物品。提供了完整的代码实现,并通过样例输入输出展示了算法的工作原理。
563

被折叠的 条评论
为什么被折叠?



