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 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 4Case 2:7 1 6
Analysis:DP problem. State transition Equation:dp[i]=d[i-1]+a[i]>a[i]?d[i-1]+a[i]:a[i]; The error code is as follows: (Critical error vs. correct code)
1#include <iostream>2#include <cstdio>3 using namespacestd;4 Const intm=100005;5 intA[m];6 7 intMain ()8 {9 intt,k=0;Tenscanf"%d",&t); One while(t--) A { - intn,i,maxn,before,begin=1, end=1; -scanf"%d",&n); the for(i=1; i<=n;i++) - { - -scanf"%d",&a[i]); + if(i==1) - { +Maxn=a[i]; Before=A[i]; A } at Else - { - if(before+a[i]<A[i]) - { -Before=A[i]; -begin=i; in } - Else to { +before+=A[i]; - } the * } $ if(before>MAXN)Panax Notoginseng { -maxn=before; the //X=begin; +End=i; A } the + } -k++; $printf"Case %d:\n", k); $printf"%d%d%d\n", maxn,begin,end); - if(t) -printf"\ n"); the - }Wuyi the return 0; -}View Code
The correct code is as follows: (use a special point case 6:2 3-6 4 3-8 to find out the error!) Add a key variable J record current A[i] position)
1#include <iostream>2#include <cstdio>3 using namespacestd;4 Const intm=100005;5 intA[m];6 7 intMain ()8 {9 intt,k=0;Tenscanf"%d",&t); One while(t--) A { - intn,i,maxn,before,begin=1, end=1, j=1;//must use a J to record the position of the current number A[i] -scanf"%d",&n); the for(i=1; i<=n;i++) - { - -scanf"%d",&a[i]); + if(i==1) - { +Maxn=a[i]; Before=A[i]; A at } - Else - { - if(before+a[i]<A[i]) - { -Before=A[i]; inJ=i;//record the current position at which begin does not change - } to Else + { -before+=A[i]; the } * $ }Panax Notoginseng if(before>MAXN) - { themaxn=before; +Begin=j;//only when the BEFORE>MAXN is changed AEnd=i; the } + - } $k++; $printf"Case %d:\n", k); -printf"%d%d%d\n", maxn,begin,end); - if(t) theprintf"\ n"); - Wuyi } the - return 0; Wu}
5thweek.problem_a hdu1003 Maximum sub-segments and