九度 题目1453:Greedy Tino

本文使用动态规划算法解决Tino携带橘子的问题,确保两旁橘子重量相等,求最大携带重量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值