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.
 

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 ;
}
上一篇:vijos1431[noip2007]守望者的逃离(背包动规)


下一篇:HDU 5615 Jam's math problem