您的位置:首页 > 其它

杭电oj-1003-Max Sum

2015-12-09 14:39 375 查看
Problem Description

Given a sequence a[1],a[2],a[3]......a
, 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.

Input

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).

Output

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.

Sample Input

2

5 6 -1 5 4 -7

7 0 6 -1 1 -6 7 -5

Sample Output

Sample Output

Case 1:

14 1 4

Case 2:

7 1 6

 这道题的题目意思是给你一个数n,然后有n个测试数据。接下来的n行,每行开头会有一个整数m,代表这个数列中有多少个数,然后接下来是m个整数。要你输出

Case i:

a b c

Case i+1:

a b c

的格式。a代表最大连续子序列之和,b代表这个子序列的开始的数的位置,c代表这个子序列的结束位置,每两个测试数据的答案之间有空行输出。

思路,这道题用dp做就很简单,首先要构造一个dp的过程,我们分别建一个存数列的数组b和存每个位置的当前最大子序列和的数组c,然后循环算出截止到当前所在位置的最大连续子序列之和。当截止到它前一个数的时候如果最大子序列之和为负数时,使当前最大值为其本身,其起点和终点坐标也为当前坐标,当其不为0时,就将之前的序列和加上其本身为当前最大子序列之和,将最大子序列之和的值以及开始坐标存起来,然后每次都进行判断,看是否更新。

代码如下:

#include <stdio.h>

#include <string.h>

#include <algorithm>

#include <iostream>

#include <math.h>

using namespace std;

int b[100005];

int c[100005];

int s1,s2,z1,z2;

int main()

{

    int n;

    scanf("%d",&n);

    int i=1;

    while(i<=n)

    {

        printf("Case %d:\n",i);

        int m;

        scanf("%d",&m);

        for(int j=0;j<m;j++)

            scanf("%d",&b[j]);

        int Max=-999;

        s1=0;

        z2=0;

        c[0]=b[0];

        for(int j=0;j<m;j++)

        {

            //判断截止到前一个数的最大子序列的和

            if(c[j-1]>=0)

            {

                //算出当前最大子序列之和,更新终点坐标

                c[j]=c[j-1]+b[j];

                z1=j;

            }

            else

            {

                //使当前最大子序列之和为其本身,起点终点也为其本身

                c[j]=b[j];

                z1=j;

                s1=j;

            }

            //更新最大子序列的和以及开始和结束坐标

            if(Max<c[j])

            {

                Max=c[j];

                s2=s1;

                z2=z1;

            }

        }

        printf("%d %d %d\n",Max,s2+1,z2+1);

        //最后一个输出结果没有空白行

        if(i!=n)

            printf("\n");

        i++;

    }

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: