G Greedy Tino
Description
Tinowrote a long long story. BUT! in Chinese...
SoI have to tell you the problem directly and discard his long long story. Thatis tino want to carry some oranges with "Carrying pole", and he mustmake 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
Thefirst line of input contains a number t, which means there are t cases of thetest data.
foreach test case, the first line contain a number n, indicate the number oforanges.
thesecond line contains n numbers, Wi, indicate the weight of each orange
nis between 1 and 100, inclusive. Wi is between 0 and 2000, inclusive. the sumof Wi is equal or less than 2000.
Output
Foreach test case, output the maximum weight in one side of Carrying pole. If youcan'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问题!
为什么自己想了这么久就没想到呢!
——路漫漫其修远兮,吾将上下而求索……
这是一个挑担子问题,话说很久以前有个人很贪心,想多挑点橘子回家,人家还有要求的。知道担子两边得一样重会轻松点。这不问题就出来,现在有这么多橘子,要你放入两边的筐里,让人家能轻轻松松多挑点回家。
dp[i][j]表示放入或不放入第i个橘子后,重量相差为j时的最优解(我选择较轻的筐的重量)。
第i个橘子分3种情况:
1、放入得较重的筐里;
2、放入较轻的筐里(这时可能会变为较重的一方);
3、不放入;
三种情况取最优解即可;
有没有听说过重量为0的橘子啊!真神奇啊。。得注意
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define N 110
#define S 2010
int dp[N][S+1];
int data[N], s[N];
int main()
{
int cases, t;
scanf("%d", &cases);
t = 1;
while(t <= cases)
{
int n;
scanf("%d", &n);
int i,j;
for(i=0; i<n; i++)
{
scanf("%d", &data[i]);
}
memset(dp, -1, sizeof(dp));
for(i=0; i<n; i++)
dp[i][data[i]] = 0;
//dp[0][0]=0;
for(i=1; i<n; i++)
{
for(j=0; j<=S; j++)
{
if(dp[i-1][j] >= 0)
{
if(data[i]+j<=S && dp[i][data[i]+j] < dp[i-1][j])
dp[i][data[i]+j] = dp[i-1][j];
if(data[i] >= j)
{
if(dp[i][data[i]-j] < dp[i-1][j] + j)
dp[i][data[i]-j] = dp[i-1][j]+j;
}
else if(data[i] < j)
{
if(dp[i][j-data[i]] < dp[i-1][j] + data[i])
dp[i][j-data[i]] = dp[i-1][j]+data[i];
}
}
}
for(j=0; j<=S; j++)
if(dp[i][j] < dp[i-1][j])
dp[i][j] = dp[i-1][j];
}
printf("Case %d: %d\n", t, dp[n-1][0]);
t++;
}
//system("pause");
return 0;
}