HDU 5616 Jam's balance(DP)
Posted ventricle
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 5616 Jam's balance(DP)相关的知识,希望对你有一定的参考价值。
题目网址: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]);
注意点是,要先将砝码的重量进行升序排序。以免漏掉第二种情况。
代码:
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 using namespace std; 5 int main(){ 6 int t,n,m; 7 int weight[205]; 8 int dp[20005]; 9 int sum; 10 scanf("%d",&t); 11 while (t--) { 12 scanf("%d",&n); 13 memset(dp, 0, sizeof(dp)); 14 dp[0]=1; 15 sum=0; 16 for (int i=0; i<n; i++) { 17 scanf("%d",&weight[i]); 18 sum+=weight[i]; 19 } 20 sort(weight, weight+n); 21 for (int i=0; i<n; i++) { 22 for (int j=sum; j>=0; j--) { 23 if(j>=weight[i])dp[j]=max(dp[j], dp[j-weight[i]]); 24 else dp[j]=max(dp[j], dp[weight[i]-j]); 25 } 26 } 27 scanf("%d",&m); 28 for (int i=0; i<m; i++) { 29 int w; 30 scanf("%d",&w); 31 printf("%s\n",dp[w]?"YES":"NO"); 32 } 33 } 34 return 0; 35 }
以上是关于HDU 5616 Jam's balance(DP)的主要内容,如果未能解决你的问题,请参考以下文章
Jam's balance HDU - 5616 (01背包基础题)
hdu 5616 Jam's balance(dp 正反01背包)
HDU 5616 Jam's balance(Jam的天平)