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