九度OJ 1453 Greedy Tino -- 动态规划

时间:2022-06-06 20:24:41

题目地址:http://ac.jobdu.com/problem.php?pid=1453

题目描述:

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.

输入:

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.

输出:

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.

样例输入:
1
5
1 2 3 4 5
样例输出:
Case 1: 7

状态转移方程:九度OJ 1453 Greedy Tino -- 动态规划

dp[i][j]表示前i个柑橘被选择(每个柑橘可能放到第一堆或者第二堆)后,第一堆比第二堆中j时(当j为负数时表示第二堆比第一堆重),两堆的最大重量和。

#include <stdio.h>

#define OFFSET 2000
#define INF 0x7fffffff int main(void){
int test, num;
int weight[101];
int dp[2][4001];
int i, j;
int zero, cnt;
int tmp1, tmp2;
int cas = 0; scanf ("%d", &test);
while (test-- != 0){
scanf ("%d", &num);
cnt = 0;
zero = 0;
for (i=1; i<=num; ++i){
scanf ("%d", &weight[++cnt]);
if (weight[cnt] == 0){
--cnt;
zero = 1;
}
}
num = cnt;
for (i=-2000; i<=2000; ++i){
dp[0][i+OFFSET] = -INF;
}
dp[0][0+OFFSET] = 0;
for (i=1; i<=num; ++i){
for (j=-2000; j<=2000; ++j){
tmp1 = -INF;
tmp2 = -INF;
if (j + weight[i] <= 2000 && dp[(i-1)%2][j+weight[i]+OFFSET] != -INF){
tmp1 = dp[(i-1)%2][j+weight[i]+OFFSET] + weight[i];
}
if (j - weight[i] >= -2000 && dp[(i-1)%2][j-weight[i]+OFFSET] != -INF){
tmp2 = dp[(i-1)%2][j-weight[i]+OFFSET] + weight[i];
}
if (tmp1 < tmp2)
tmp1 = tmp2;
if (tmp1 < dp[(i-1)%2][j+OFFSET])
tmp1 = dp[(i-1)%2][j+OFFSET];
dp[i%2][j+OFFSET] = tmp1;
}
}
printf ("Case %d: ", ++cas);
if (dp[num%2][0+OFFSET] == 0){
puts (zero == 1 ? "0" : "-1");
}
else
printf ("%d\n", dp[num%2][0+OFFSET]/2);
} return 0;
}