九度 题目1453:Greedy Tino

九度 题目1453:Greedy Tino题目描述:Tinowrotealonglongstory.BUT!inChinese…SoIhavetotellyoutheproblemdirectlyanddiscardhislonglongstory.That

题目描述:

 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
动态规划算法解决,转移方程如下:
九度 题目1453:Greedy Tino方程含义是:在前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分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/68207.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注