Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 197869 Accepted Submission(s): 46229
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
对于一个数,决策只有两种,要么让他跟前面的并在一起,要么前面的扔掉,从这个数开始取。
用dp结构体来表示,比较直观
若把前面的一段与A[i]合并,则当前点的l为dp[i-1].l保持不变,r=dp[i-1].r+1,因为此时A[i]算了进去;
若直接从A[i],那么令dp[i].l=dp[i].r=i即可,dp[i].val=A[i]。
最后找到一个最大的dp[i].val即可
代码:
#include <stdio.h> const int N = 100010; struct info { int val; int l, r; }; info dp[N]; int arr[N]; int main(void) { int tcase, n, i; scanf("%d", &tcase); for (int q = 1; q <= tcase; ++q) { scanf("%d", &n); for (i = 1; i <= n; ++i) scanf("%d", arr + i); dp[1].val = arr[1]; dp[1].l = 1; dp[1].r = 1; for (i = 2; i <= n; ++i) { int a = dp[i - 1].val + arr[i]; int b = arr[i]; if (a >= b) { dp[i].val = a; dp[i].l = dp[i - 1].l; dp[i].r = dp[i - 1].r + 1; } else { dp[i].l = dp[i].r = i; dp[i].val = arr[i]; } } int indx = 1; for (i = 1; i <= n; ++i) if (dp[i].val > dp[indx].val) indx = i; printf("Case %d: %d %d %d %s", q, dp[indx].val, dp[indx].l, dp[indx].r, q != tcase ? " " : ""); } return 0; }