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
动态规划算法解决,转移方程如下:
方程含义是:在前i个物品中进行选择,分为两堆,第一堆比第二堆重j千克时,两堆加起来的最大总重量!(注意:j可以为负数)
代码如下:
#include <stdio.h> #include <string.h> #define OFFSET 2000//因为j有正负,所以添加一个偏移量,方便做题 #define INF 0x7fffffff int wi[101]; int dp[101][4001]; int max(int a, int b, int c){ int flag = a; if(flag < b){ flag = b; } if(flag < c){ flag = c; } return flag; } void init() { for(int i=0;i<40001;i++) dp[0][i] = -INF; dp[0][OFFSET] = 0;//core } int main(){ int t, n; scanf("%d", &t); for(int i = 0; i < t; i++){ scanf("%d", &n); wi[0] = 0; bool hasZero = false; int cnt = 0; for(int j = 0; j < n; j++){ scanf("%d", &wi[++cnt]); if(wi[cnt] == 0){ hasZero = true; cnt--; } } n = cnt; init(); for(int j = 1; j <= n; j++){ for(int k = -2000; k <= 2000; k++){ dp[j][k+OFFSET] = max(dp[j-1][k-wi[j]+OFFSET]+wi[j], dp[j-1][k+wi[j]+OFFSET]+wi[j], dp[j-1][k+OFFSET]); } } printf ("Case %d: ", i+1); if(dp[n][0+OFFSET] == 0){ if(hasZero == true){ printf("0\n"); }else{ printf("-1\n"); } }else{ printf("%d\n", dp[n][0+OFFSET]/2); } } return 0; }
原文地址:http://blog.csdn.net/j754379117/article/details/44016141