Jam's balance

来源:互联网 发布:mac结构图app免费 编辑:程序博客网 时间:2024/05/24 06:05
链接:

题目:Jim has a balance and N weights. $(1 \leq N \leq 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.

题意:有一些砝码和一个物品,问是否可以使天平平衡。

分析:由于是一组砝码多组物品挨个测试,所以对所有砝码分成两组能够组成的差进行预处理,之后用查询的方式解决比较好。首先在录入砝码的时候分别记录其重量以及重量的相反数,这样就可以直接由循环来直接得出所有的结果,+的代表放在左边,-的放在右边,+-都选择或者都不选择代表这个砝码不放在天平上。之后把所有记录依次与结果集计算,如果和>0代表可以有这样的结果,如果其不在结果集中就放入,否则不用管。最后查询即可。

题解:
#include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <queue>#include <stack>#include <vector>#include <map>#include <string>#include <cstring>#include <functional>#include <cmath>#include <cctype>#include <cfloat>#include <climits>#include <complex>#include <deque>#include <list>#include <set>#include <utility>using namespace std;set<int> s;vector<int> v;bool is[2010];vector<int> te;int main(){//freopen("in.txt", "r", stdin);int T;cin >> T;while (T--){int n, temp;memset(is, 0, sizeof is);v.clear();s.clear();te.clear();cin >> n;for (int i = 0; i < n; i++) {cin >> temp;v.push_back(temp);v.push_back(-temp);}sort(v.begin(), v.end(),greater<int>());te.push_back(0);is[0] = true;for (int i = 0; i < v.size();i++){int size = te.size();for (int j = 0; j < size; j++){if (v[i] + te[j] >= 0 && !is[v[i] + te[j]]) {te.push_back(v[i] + te[j]);s.insert(v[i] + te[j]);is[v[i] + te[j]] = true;}}}int t;cin >> t;for (int i = 0; i < t; i++){int w;cin >> w;if (s.count(w))cout << "YES" << endl;elsecout << "NO" << endl;}}return 0;}

0 0