Title:
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 is b etween-1000 and 1000).
Output
For the test case, you should output of the lines. The first line was "Case #:", # means the number of the the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end posi tion of the sub-sequence. If there is more than one result, output the first one. Output a blank line between 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
Ideas:
Classic Primer DP, the difficulty is small, mainly because he was too careless WA 4 times, record a long memory.
The place of WA is that the last position of the record sub-sequence is not initialized to 1, resulting in if the maximum subsequence is the first element at the end of 0.
Code:
#include <bits/stdc++.h> using namespace std; #define MAXN 100000+10 #define M (A, B)
Memset (A, B, sizeof (a)) int a[maxn], DP[MAXN], first, last, maxsum;
void Do () {M (DP, 0);
M (A, 0);
int n;
scanf ("%d", &n);
for (int i = 1; I <= n; ++i) scanf ("%d", &a[i]);
DP[1] = a[1];
for (int i = 2; I <= n; ++i) dp[i] = max (a[i]+dp[i-1], a[i]);
Maxsum = dp[1];
last = 1;
for (int i = 2; I <= n; ++i) if (Dp[i] > maxsum) {maxsum = Dp[i];
last = i;
} int temp = Maxsum;
for (int i = last; I >= 1; i) {temp-= a[i];
if (!temp) first = i;
}} int main () {int T;
scanf ("%d", &t);
for (int i = 1; I <= T; ++i) {do ();
printf ("Case%d:\n%d%d%d\n", I, Maxsum, first, last);
if (i! = T) printf ("\ n");
} return 0; }