HDU 1003-最大子段和

题目链接

设a[1-n]为输入的数组,DP[i]表示以i位置结尾最大的子段和,当DP[i-1]大于等于0时表示DP[i-1]对a[i]有贡献则DP[i]=DP[i-1]+a[i]否则DP[i]=a[i],这里代码中省略了a数组。

#include <iostream>  
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <string>
#include <string.h>
#include <cmath>
#include <sstream>
#include <set>
#include <map>
#include <functional>
#include <queue>
#include <vector>
using namespace std;

const int maxn = 100010;
int arr[maxn], dp[maxn];
int t, n, a, res;

int main()
{
    cin >> t;
    int num = t;
    int Case = 0;

    while (t--)
    {
        int Max, start, lst, fst, n;
        lst = fst = start = 1;

        cin >> n;
        for (int i = 1; i <= n; i++)
            cin >> dp[i];
        Max = dp[1];
        for (int i = 2; i <= n; i++)
        {
            if (dp[i - 1] >= 0)
            {
                dp[i] = dp[i - 1] + dp[i];
            }
            else
                start = i;
            if (dp[i] > Max)
            {
                fst = start;//更新起始位置
                lst = i;
                Max = dp[i];
            }
        }
        cout << "Case " << ++Case << ":\n";
        cout << Max << " " << fst << " " << lst << ((Case == num) ? "\n" : "\n\n");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值