HDU 1003 Max Sum

Max Sum

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

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

1
2
3
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5

Sample Output

1
2
3
4
5
Case 1:
14 1 4

Case 2:
7 1 6

Idea

求最大子数组,要注意的是全是0和负数的情况(被坑了一下)
原题地址:http://acm.hdu.edu.cn/showproblem.php?pid=1003

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <stdio.h>
#define MAXN 100005

typedef struct{ int s, l, r; }Sum;
Sum MaxSub(int a[], int n);

int main(void)
{
int ar[MAXN], c, n, i, j;
Sum x = {0, 0, 0};
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
scanf("%d", &c);
for(i = 1; i <= c; i++)
{
scanf("%d", &n);
for(j = 1; j <= n; j++)
scanf("%d", &ar[j]);
x = MaxSub(ar, n);
printf("Case %d:\n%d %d %d", i,x.s, x.l, x.r);
if(i != c) printf("\n\n");
else printf("\n");
}
}

Sum MaxSub(int a[], int n)
{
int i, s = 0, l = 1, r = 1, b;
Sum sum = {a[1], 0, 0};
for(i = 1; i <= n; i++) { if(s >= 0)
{
s += a[i];
if(a[i] > 0) r = i;
}
else
{
s = a[i];
r = l = i;
}
if(s >= sum.s)
{
sum.s = s;
sum.l = l;
sum.r = r;
}
}
return sum;
}
坚持原创技术分享,您的支持将鼓励我继续创作!