hdu=1003 Max Sum

来源:互联网 发布:python接收命令行参数 编辑:程序博客网 时间:2024/06/15 11:00
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
25 6 -1 5 4 -77 0 6 -1 1 -6 7 -5
 

Sample Output
Case 1:14 1 4Case 2:7 1 6
 

题目大意:输入一个整数t,接下来有t组测试数据,每一组输入一个数n,接着输入n个整数,计算并输出出这n个整数的最大和、开始位置和结束位置。



以 6 -7 5 -1 4为例,以6为起始位置时,6+(-7)=-1,第三项5加上前两项和(-1)之后变小,不如以5为起始位置。

算法:用sum存入前n项和,如果加到第x项时sum<0,初始化sum并以x+1位置为起始位置累加sum和。计算过程中比较sum与max的大小并更新max值,更新max值的同时保存起始位置与结束位置。


AC代码

#include <stdio.h>#include <string.h>int a[100010];int main(){    int t,i,k,n,sum,max,start = 0,end = 0,temp;    scanf("%d",&t);    for(k=1;k<=t;k++){        memset(a, 0, sizeof(a));        sum=0;temp=0;max=-1010;// 初始化数据        scanf("%d",&n);        for(i=0;i<n;i++)            scanf("%d",&a[i]);        for(i=0;i<n;i++){            sum=sum+a[i];//累加前n项和            if(sum>max){                start=temp;                max=sum;                end=i;            }             //sum>max时,更新max值同时保存起始位置和结束位置            if(sum<0)            {                sum=0;                temp=i+1;            }           //sum<0时初始化sum并以下一项为起始位置        }        printf("Case %d:\n%d %d %d\n",k,max,start+1,end+1);        if(k!=t)           printf("\n");    }}

ps. 两个if的语句不能调换位置,第一次写的时候wa了一次。如果调换位置在全部输入负数时会出错。



原创粉丝点击