HDU 1003 Max Sum

Posted Reqaw’s Blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 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 -15 4 -7
7 0 6 -1 1 -6 7 -5
 

 

Sample Output
Case 1: 14 1 4
 
 
Case 2: 7 1 6
题意描述:
输入一串数字为N N(1<=N<=100000)和N个范围-1000到1000的整型数
计算并输出该串数字的最大子串(连续)和以及该子串的起始位置和终止位置
解题思路:
该题还是比较考察思维的,属于简单的DP问题。遍历每个元素,将其累加到sum上,并每次判断sum是否大于max,若大于max则更新sum后,将始末位置也更新一下;若sum<0,表示该数是一个很大的负数需要重新开始累加sum,寻找下一个可能存在的最大子串和。
代码实现:
 1 #include<stdio.h>
 2 int main()
 3 {
 4     int T,t,n,a[100010],i,sum,s,f,c=0,max;
 5     scanf("%d",&T);
 6     while(T--)
 7     {
 8         scanf("%d",&n);
 9         for(i=1;i<=n;i++)
10             scanf("%d",&a[i]);
11         sum=0;
12         max=-99999999;//注意将max赋值为一个较小的赋值 
13         t=1;
14         for(i=1;i<=n;i++){
15             sum += a[i];
16             if(sum > max){
17                 max=sum;
18                 s=t;
19                 f=i;
20             }
21             if(sum < 0){
22                 sum=0;
23                 t=i+1;
24             }
25         }
26         printf("Case %d:\n%d %d %d\n",++c,max,s,f);
27         if(T != 0)
28         printf("\n");
29     }
30     return 0;
31 } 

易错分析:

1、注意格式问题

2、注意max的初始化

以上是关于HDU 1003 Max Sum的主要内容,如果未能解决你的问题,请参考以下文章

MAX SUM(HDU_1003——dp)

hdu-1003 Max Sum

HDU1003:Max Sum

HDU 1003 Max Sum

HDU - 1003 Max Sum

hdu 1003 Max Sum