HDU 5616 Jam's balance 背包DP
2016-01-30 23:39
453 查看
Jam's balance
[align=left][b]Problem Description[/b][/align]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.
[align=left][b]Input[/b][/align]
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.
[align=left][b]Output[/b][/align]
You should output the "YES"or"NO".
[align=left][b]Sample Input[/b][/align]
1
2
1 4
3
2
4
5
[align=left][b]Sample Output[/b][/align]
NO
YES
YES
Hint
For the Case 1:Put the 4 weight alone
For the Case 2:Put the 4 weight and 1 weight on both side
[align=left][b]题意:[/b][/align]
Jam有NN个砝码和一个没有游标的天平,现在给他(1 \leq N \leq 20)(1≤N≤20)个砝码,砝码可以放左边,也可以放右边,问可不可以测出所问的重量, 问的个数为(1 \leq M \leq 100)(1≤M≤100)个.
[align=left] [/align]
[align=left][b]题解:[/b][/align]
[align=left] 这道题可以放左边,可以放右边,N=20N=20显然每种状态都枚举是不太现实的,因为每组砝码都可以变成很多种重量,当然也不排除有人乱搞过了这一题,其实这道题是一道贪心的思想,我们看到ww不大,所以可以用0101背包扫一次,当然这还是不够的,这只能放一边,考虑到可以放另一边,就是可以有减的关系,所以反着再背包一遍,注意要判断边界。[/align]
[align=left] [/align]
#include<bits/stdc++.h> using namespace std ; typedef long long ll; const int N = 5000; int n,m,a[N+10],dp[N+10],sum; void DP() { memset(dp,0,sizeof(dp)); dp[0]= 1; for(int i = 1; i<= n; i++) { for(int k=2;k;k--) for(int j = sum*2;j>=a[i];j--) { dp[j]|=dp[j-a[i]]; } } } int main() { int T,x; scanf("%d",&T); while(T--) { scanf("%d",&n);sum=0; for(int i = 1;i <= n; i++) scanf("%d", &a[i]),sum+=a[i]; DP(); scanf("%d", &m); for(int i = 1; i<= m; i++) { scanf("%d", &x); int g = x+sum&&sum+x>=0&&dp[x+sum]; if(g)printf("YES\n"); else printf("NO\n"); } } return 0; }
相关文章推荐
- Oracle 11G RAC开启和关闭归档日志
- Android Material Design控件学习(二)——NavigationView的学习和使用
- 【Android】【笔记】《Android 入门经典》part 7 Intent
- 集训队专题(2)1005 A Simple Math Problem
- 嵌入式Linux之Linux内核的装载
- Longest Common Prefix
- python爬虫基础登----网站登录
- 2016第4周六
- jqgrid常用操作
- 【Android】【笔记】《Android 入门经典》part 6 Activity
- POJ1986(LCA应用:求两结点之间距离)
- mysql-XtraBackup备份
- Sqlite3 批量导入数据
- Nginx+Varnish
- 1041. 考试座位号(15)
- 使用yum源安装CDH Hadoop集群
- 【Android】【笔记】《Android 入门经典》part 5 程序调试
- 蓝桥杯 - 最小乘积(基本型)
- C++基本概念——赋值&&初始化
- iOS 安全攻防系列(三):sqlite3数据库