首页 > 其他 > 详细

九度 题目1453:Greedy Tino

时间:2015-03-02 13:16:10      阅读:598      评论:0      收藏:0      [点我收藏+]
题目描述:

 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;
}

九度 题目1453:Greedy Tino

原文:http://blog.csdn.net/j754379117/article/details/44016141

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!