Jam's balance

链接:

题目: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;
			else
				cout << "NO" << endl;
		}
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值