题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3578
Greedy Tino
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1970 Accepted Submission(s): 657
Problem Description
Tino wrote a long long story. BUT! in Chinese...
So I have to tell you the problem directly and discard his long long story. That is tino want to carry some oranges with "Carrying pole", and he must make two side of the Carrying pole are the same weight. Each orange have its' weight. So greedy tino want to know the maximum weight he can carry.
Input
The first line of input contains a number t, which means there are t cases of the test data.
for each test case, the first line contain a number n, indicate the number of oranges.
the second line contains n numbers, Wi, indicate the weight of each orange
n is between 1 and 100, inclusive. Wi is between 0 and 2000, inclusive. the sum of Wi is equal or less than 2000.
Output
For each test case, output the maximum weight in one side of Carrying pole. If you can't carry any orange, output -1. Output format is shown in Sample Output.
Sample Input
1 5 1 2 3 4 5
Sample Output
Case 1: 7
就像一个天平一样,寻找两边能凑成重量相同的最大的重量。
注意特殊情况0
前i个物品选择之后 ,j表示左边-右边 重量差,会存在负数 ,-2000——2000 加上0ffset
这个dp [ i ][ j ]表示总重量。
dp[ 0 ][ i ]=0
第 i 个选择装在左、右、不装
dp[ i ][ j ]=max( dp[ i-1 ][ j-w[i] ]+w[ i ],dp[ i-1 ][ j+w[i] ]+w[i], dp[ i-1][ j ])
//疑问初始化的时候为啥dp[i][j+OFFSET]=-INF
#include<iostream>
using namespace std;
int t,n;
int w[200];
int dp[200][4050];
#define OFFSET 2010
#define INF 0x3f3f3f3f
int main(){
cin>>t;
int cas=1;
while (t--){
cin>>n;
bool isPositive=false;
int num=0;
for(int i=1;i<=n;i++) {
cin>>w[++num];
//处理输入
if(w[num]==0){
isPositive= true;
num--;
}
}
for(int i=-2000;i<=2000;i++) dp[0][i+OFFSET]=-INF; //不知道为何一定是负无穷
dp[0][0+OFFSET]=0;
n=num;
for(int i=1;i<=n;i++){
for(int j=-2000;j<=2000;j++){
//判断是否存在
int t1,t2;
t1=-INF;
t2=-INF;
if(j-w[i]>=-2000 && dp[i-1][j-w[i]+OFFSET]!=-INF){
t1=dp[i-1][j-w[i]+OFFSET]+w[i];
}
if(j+w[i]<=2000 && dp[i-1][j+w[i]+OFFSET]!=-INF){
t2=dp[i-1][j+w[i]+OFFSET]+w[i];
}
if(t1<t2){
t1=t2;
}
if(t1<dp[i-1][j+OFFSET])
t1=dp[i-1][j+OFFSET];
dp[i][j+OFFSET]=t1;
}
}
if(dp[n][0+OFFSET]==0){
if(isPositive) cout<<"Case "<<cas++<<": "<<0<<endl;
else cout<<"Case "<<cas++<<": "<<-1<<endl;
}
else {
cout<<"Case "<<cas++<<": "<<dp[n][0+OFFSET]/2<<endl;
}
}
return 0;
}