码迷,mamicode.com
首页 > 其他好文 > 详细

Hdoj 1003

时间:2018-01-27 23:11:03      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:each   ace   输出   using   main   动态   cas   max   down   

原题链接

描述

Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.

输入描述

The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).

输出描述

For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.

样例输入

2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5

样例输出

Case 1:
14 1 4

Case 2:
7 1 6

思路

最大连续子列和问题,典型的动态规划。需要注意的是格式问题。
首先找到状态转移方程sum[i] = max{sum[i-1] + a[i-1], a[i-1]},维护起始值即可确定开始点和结束点。
实际上,也不需要开数组,sum和a随时变化也可以。这样能将空间复杂度降到O(1),而时间复杂度是O(n)。

代码

#include <bits/stdc++.h>   
using namespace std;  

int main()
{
    int n; cin >> n;
    for(int ii = 0; ii < n; ii++)
    {
        int num; cin >> num;
        int f = 0, l = 0, t = 0;
        int max, sum;
        cin >> max; sum = max;
        for(int i = 1; i < num; i++)
        {
            int a;
            cin >> a;
            if(sum >= 0)
            {
                sum += a;
            }
            else
            {
                sum = a;
                t = i;
            }
            if(sum > max)
            {
                max = sum;
                f = t;
                l = i;
            }
        }
        printf("Case %d:\n%d %d %d\n", ii + 1, max, f + 1, l + 1);
        if(ii < n - 1) printf("\n");
    }
}

Hdoj 1003

标签:each   ace   输出   using   main   动态   cas   max   down   

原文地址:https://www.cnblogs.com/HackHarry/p/8365362.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!