题目网址:http://acm.hdu.edu.cn/showproblem.php?pid=5616

题目:

Jam's balance

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1810    Accepted Submission(s): 754

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.
 

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.
 
Output
 
You should output the "YES"or"NO".
 
Sample Input
1
2
1 4
3
2
4
5
 
Sample Output
NO
YES
YES
 
题意:
给若干个砝码和一个天平,再给若干个要称的重量,问是否能由以上的玛法和天平秤出。
 
思路:
因为砝码可以放在天平两侧,所以砝码重量之和以及重量之差 都能秤出来。所以状态转移分两个:
1.该重量大于等于当前遍历的砝码重量时:dp[j]=max(dp[j], dp[j-weight[i]]);
2.该重量小于当前遍历的砝码重量时:dp[j]=max(dp[j], dp[weight[i]-j]);
注意点是,要先将砝码的重量进行升序排序。以免漏掉第二种情况。
 
代码:
 #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int main(){
int t,n,m;
int weight[];
int dp[];
int sum;
scanf("%d",&t);
while (t--) {
scanf("%d",&n);
memset(dp, , sizeof(dp));
dp[]=;
sum=;
for (int i=; i<n; i++) {
scanf("%d",&weight[i]);
sum+=weight[i];
}
sort(weight, weight+n);
for (int i=; i<n; i++) {
for (int j=sum; j>=; j--) {
if(j>=weight[i])dp[j]=max(dp[j], dp[j-weight[i]]);
else dp[j]=max(dp[j], dp[weight[i]-j]);
}
}
scanf("%d",&m);
for (int i=; i<m; i++) {
int w;
scanf("%d",&w);
printf("%s\n",dp[w]?"YES":"NO");
}
}
return ;
}

最新文章

  1. 工作笔记--哪些bug应由研发发现?
  2. 为jQuery的$.ajax设置超时时间
  3. OC学习1
  4. POJ 3660
  5. wcf自身作为宿主的一个小案例
  6. Linux系统各发行版镜像下载(2)
  7. DDX_Text (MFC)
  8. 编程之美 两个叶子的节点之间 最大距离 变种 leecode
  9. RH033读书笔记(11)-Lab 12 Configuring the bash Shell
  10. SGU 194 Reactor Cooling ——网络流
  11. 九度oj题目1002:Grading
  12. .net开发微信(1)——微信订阅号的配置
  13. echarts实时数据图表
  14. BZOJ1319Sgu261Discrete Roots——BSGS+exgcd+原根与指标+欧拉定理
  15. Codeforces Round #487 (Div. 2) C - A Mist of Florescence
  16. C++ template一些体悟(3)
  17. python程序如何脱离ide而在操作系统上执行
  18. 【BZOJ3821/UOJ46】玄学(二进制分组,线段树)
  19. image 样式设置
  20. Hadoop生态圈-zookeeper本地搭建以及常用命令介绍

热门文章

  1. SpringBoot 2.0 + Nacos + Sentinel 流控规则集中存储
  2. C#面试题目整理(一)
  3. Java 集合转换(数组、List、Set、Map相互转换)
  4. PHP的跨域问题
  5. java架构之路-(mysql底层原理)Mysql之让我们再深撸一次mysql
  6. tomcat下c3p0连接池配置问题
  7. Java 文章链接
  8. 一台机器上搭建多个redis实例的配置文件修改部分
  9. 利用百度云接口实现车牌识别&#183;python
  10. Angular 文件上传、下载