杭电oj-1003-Max Sum

Problem Description
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.
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;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值