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
题目大意:有一个天平,有 n 个砝码,砝码可以放在任意一个盘,若干次询问 m 是否可以用已有砝码称出。
从第一个开始更新状态,OK[i][j] 表示考虑到第 i 个时 重量 j 是否可以被称出。1 ~ n 更新一遍即可。
代码:
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn1 = 25; const int maxn2 = 2 * 1e3 + 5; bool ok[maxn1][maxn2]; int a[maxn1]; int n; void init() { memset(ok,false,sizeof(ok)); ok[0][0] = ok[0][a[0]] = true; for(int i = 1;i < n; ++i) { for(int j = 0;j < maxn2; ++j) { if(!ok[i - 1][j]) continue; ok[i][j] = ok[i - 1][j]; ok[i][j + a[i]] = true; if(j > a[i]) ok[i][j - a[i]] = true; else ok[i][a[i] - j] = true; } } } int main() { int t,m,p; scanf("%d",&t); while(t--) { scanf("%d",&n); for(int i = 0;i < n; ++i) scanf("%d",&a[i]); init(); scanf("%d",&p); while(p--) { bool r = false; scanf("%d",&m); if(ok[n - 1][m]) printf("YES\n"); else printf("NO\n"); } } return 0; }
本文介绍了一个使用天平和有限数量的砝码来判断能否测量特定重量的算法。通过递增更新状态的方式,记录哪些重量可以通过现有砝码组合实现。最终确定目标重量是否可测。
1591

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



