HDU-1003 Max Sum

Posted 启动

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU-1003 Max Sum相关的知识,希望对你有一定的参考价值。

Max Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 252943    Accepted Submission(s): 60001


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
Case 1: 14 1 4 Case 2: 7 1 6

 

题目的意思是求一段连续的和最大序列,如果有多个序列,则输出第一个。
代码思想用当前部分和与之前的最大部分和比较,若比之前的大,则更新。
若当前部分和小于零,即可以废弃当前部分和,寻求下一个。
最后判断全是负数的情况
 
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     //freopen("in.txt","r",stdin);
 9     int T, n, subsum, ans;              //subsum:当前部分和,ans:答案
10     int N = 1;
11     int Sta, End, Sta1;            //Sta:至今最大和起始位置,End:至今最大和终止位置,Sta1当前部分和的起始位置
12     int a[110000];
13     scanf("%d",&T);
14     while( T--) {
15         scanf("%d",&n);
16         if(N != 1) printf("\n");
17         printf("Case %d:\n",N++);
18         ans = -1, Sta = End = Sta1 = 1, subsum = 0;
19         for(int i = 1 ; i <= n ; i++ ) {
20             scanf("%d",&a[i]);
21             subsum += a[i];
22             if(subsum < 0) {Sta1 = i+1 ; subsum = 0;}//当前部分和是负数,则遗弃当前段部分和,寻找下一段
23             else {
24                 if(subsum > ans) {//当前部分和大于之前的某一段部分和,则更新
25                         Sta = Sta1;
26                         End = i;
27                         ans = subsum ;
28                 }
29             }
30 
31         }
32         if(ans == -1) {//判断全是负数的情况
33             ans = -100000;
34             for(int i = 1; i <= n; i++) {
35                 if(ans < a[i]) {
36                     ans = a[i];
37                     Sta = End = i;
38                 }
39             }
40             printf("%d %d %d\n",ans ,Sta, End);
41         }
42         else
43             printf("%d %d %d\n",ans, Sta, End);
44      }
45     return 0;
46 }

 

 
 

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

hdu-1003 Max Sum

HDU1003:Max Sum

HDU 1003 Max Sum

HDU - 1003 Max Sum

hdu 1003 Max Sum

Max Sum HDU - 1003