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
/*
dp[i][j]表示前i个柑橘被选择后,第一堆比第二堆重j时,两堆的最大总重量和
*/
#include<stdio.h>
#define INF 0x7fffffff //首位符号位,剩下31位均为1,表示int最大值
#define OFFSET 2000 //偏移量
int dp[101][4001];
int list[101];
int main() {
int T;
int cas = 0;
scanf_s("%d", &T);
while (T-- != 0) {
int n;
scanf_s("%d", &n);
bool HaveZero = false;
int cnt = 0;
for (int i = 1; i <= n; i++) {
scanf_s("%d", &list[++cnt]);
if (list[cnt] == 0) {
cnt--;
HaveZero = true;
}
}
n = cnt;
for (int i = -2000; i <= 2000; i++) {
dp[0][i + OFFSET] = -INF;
}//初始化所有dp[0][i]都是负无穷
dp[0][0 + OFFSET] = 0;
for (int i = 1; i <= n; i++) {
for (int j = -2000; j <= 2000; j++) {
int tmp1 = -INF;
int tmp2 = -INF;
if (j + list[i] <= 2000 && dp[i - 1][j + list[i] + OFFSET] != -INF) {
//当状态可以由放在第一堆转移而来
tmp1 = dp[i - 1][j + list[i] + OFFSET] + list[i];
}
if (j - list[i] >= -2000 && dp[i - 1][j - list[i] + OFFSET] != -INF) {
//当状态可以由放在第二堆转移而来
tmp2 = dp[i - 1][j - list[i] + OFFSET] + list[i];
}
if (tmp1 < tmp2) {
tmp1 = tmp2;
}
if (tmp1 < dp[i - 1][j + OFFSET]) {
//将tmp1与当前柑橘不放入任何堆的原状态值进行比较,取较大的
tmp1 = dp[i - 1][j + OFFSET];
}
dp[i][j + OFFSET] = tmp1;
}
}
printf("Case %d: ", ++cas);
if (dp[n][0 + OFFSET] == 0) {
puts(HaveZero == true ? "0" : "-1");
}
else printf("%d\n", dp[n][0 + OFFSET] / 2);
}
return 0;
}