1. 程式人生 > >HDU - 3578 Greedy Tino 01揹包 設基準點

HDU - 3578 Greedy Tino 01揹包 設基準點

 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

題解:dp[i][j] 表示前i個物品 差值為j時的最大值 因為差可能為負數,物品的總重量不超2000 所以開一個4000的,把2000作為基準就好

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define lowbit(x) (x&(-x))
#define INF 0x3f3f3f3f
const int N=110;
typedef long long ll;
int n,w[110],dp[110][4100];
int main()
{
	int T,nn=1;
	scanf("%d",&T);
    while(T--)
    {
    	scanf("%d",&n);
    	for(int i=1;i<=n;i++)scanf("%d",&w[i]);
    	memset(dp,-INF,sizeof(dp));
    	for(int i=0;i<=n;i++)dp[i][2000]=0;
    	for(int i=1;i<=n;i++)
        {
            for(int k=-2000;k<=2000;k++)
            {
                int j=k+2000;
//              cout<<j-w[i]<<endl;
                dp[i][j]=dp[i-1][j];
                if(j+w[i]<=4000) dp[i][j]=max(dp[i][j],dp[i-1][j+w[i]]+w[i]);
                if(j-w[i]>=0) dp[i][j]=max(dp[i][j],dp[i-1][j-w[i]]+w[i]);
            }
//            cout<<dp[i][2001]<<endl;
        }
        printf("Case %d: ",nn++);
        if(dp[n][2000]>0) printf("%d\n",dp[n][2000]/2);
        else
        {
            int flag=-1;
            for(int i=1;i<=n;i++)
                if(w[i]==0)
                    flag=0;
            printf("%d\n",flag);
        }
    }
	return 0;
}