HDU - 1003 Max Sum (两种做法:DP和分治)

首先介绍分治的方法:
在分治求最大连续和的过程中,维护一个区间,找到最大连续和的时候就替换区间

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>

using namespace std;

const int MAXN = 100000+10;

typedef struct node {
    int l, r;
    int w;
}Num;
Num num[MAXN];


Num max_sum(int x, int y) {
    if(y-x == 1) {
        Num cns;
        cns.w = num[x].w;
        cns.l = x;
        cns.r = x;
        return cns;
    }
    int m = x+(y-x)/2;
    Num cns;
    Num num1 = max_sum(x, m);
    Num num2 = max_sum(m, y);
    if(num1.w <= num2.w) {
        cns = num2;
    }else cns = num1;
    int res = 0;
    int l, r;
    int L = num[m-1].w;
    int R = num[m].w;
    for (int i = m-1; i >= x; i--) {
        res +=num[i].w;
        if(L <= res) {
            L = res;
            l = i;
        }
    }
    res = 0;
    for (int i = m; i < y; i++) {
        res+= num[i].w;
        if(R<=res) {
            R = res;
            r=i;
        }
    }
    if(cns.w <= L+R) {
        cns.w=L+R;
        cns.l = l;
        cns.r = r;
    }
    return cns;
}

int main() {
     int t;
     cin >> t;
     int kase = 0;
     while(t --) {
        if(kase) cout << endl;
        kase ++;
        int n;
        cin >> n;
        for (int i = 1; i <= n; i++) {
            cin >> num[i].w;
        }
        cout << "Case "<< kase << ":" << endl;
        Num ans = max_sum(1, n+1);
        cout << ans.w << " " << ans.l << " " << ans.r << endl;
        
     }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值