Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 38854 Accepted Submission(s): 8400
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
Author
Ignatius.L
1
//
动态规划
2
#include
<
iostream
>
3
using
namespace
std;
4
int
main()
5
{
6
int
T,N,num,start,end;
7
cin
>>
T;
//
输入的是有几行数据
8
for
(
int
i
=
0
;i
<
T;i
++
)
9
{
10
cin
>>
N;
//
输入的是有几列数据
11
int
max
=-
1001
,sum
=
0
,temp
=
1
;
//
一些数据的初始化
12
for
(
int
j
=
0
;j
<
N;j
++
)
13
{
14
cin
>>
num;
//
处理每一个输入的数据
15
sum
+=
num;
16
if
(max
<
sum)
//
如果加上比以前的大则要记录
17
{
18
max
=
sum;
19
start
=
temp;
20
end
=
j
+
1
;
//
指定的是当前的位置
21
}
22
if
(sum
<
0
)
23
{
24
sum
=
0
;
25
temp
=
j
+
2
;
//
将头结点向后移动一位
26
}
27
}
28
cout
<<
"
Case
"
<<
i
+
1
<<
"
:
"
<<
endl
<<
max
<<
"
"
<<
start
<<
"
"
<<
end
<<
endl;
29
if
(i
!=
T
-
1
)
//
最后一行不要换行
30
cout
<<
endl;
31
}
32
return
0
;
33
}