Max SumTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 318180 Accepted Submission(s): 75636 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 |
参考题解
转自https://www.cnblogs.com/tommychok/p/5199668.html
题目大意:给定序列个数n及n个数,求该序列的最大连续子序列的和,要求输出最大连续子序列的和以及子序列的首位位置
解题思路:经典DP,可以定义dp[i]表示以a[i]为结尾的子序列的和的最大值,因而最大连续子序列及为dp数组中的最大值。
状态转移方程:dp[1] = a[1]; //以a[1]为结尾的子序列只有a[1];
i >= 2时, dp[i] = max( dp[i-1]+a[i], a[i] );
dp[i-1]+a[i] > a[i]时,即dp[i-1](以a[i-1]为结尾的子序列的和的最大值)的值为正,那么dp[i-1]则对dp[i]有贡献,
dp[i-1]+a[i] < a[i]时,即dp[i-1] < 0,那么抛弃它,dp[i] = a[i]
例子:序列 6 -7 5 2 -3, 则dp[i]分别为 6 -1 5 7 4,注意dp[2]直接用a[2]表示,因为dp[1] = -1 < 0; 最后最大子序列和即为dp数组中的最大值 5;
至于位置的记录,则再每次获取到最大值时更新即可。另外此题是从前往后更新,可直接使用a[i]数组而省下一个dp数组。
/* HDU 1003 Max Sum --- 经典DP */
#include <cstdio>
#include <cstring>
int dp[100005];
int main()
{
#ifdef _LOCAL
freopen("D:\\input.txt", "r", stdin);
#endif
int t, n;
int kase = 0;
int fst, lst, maxSum; //记录首位位置以及最大和
int start; //start是用于记录中间变化的起点的
scanf("%d", &t);
while (t--){
scanf("%d", &n);
for (int i = 0; i < n; ++i){
scanf("%d", dp + i);
}//for(i)
start = fst = lst = 0;
maxSum = dp[0];
for (int i = 1; i < n; ++i){
//dp[i] = MAX(dp[i - 1] + dp[i], dp[i]);
//由于是从前往后更新的,可以省下一个dp数组
if (dp[i-1] >= 0){
dp[i] = dp[i - 1] + dp[i];
}
else{
start = i; //抛弃dp[i-1],则起点发生变化
}
if (dp[i] > maxSum){
//若当前求得的子序列和最大,进行更新
maxSum = dp[i];
fst = start;
lst = i;
}
}
if (kase){
printf("\n");
}
printf("Case %d:\n", ++kase);
printf("%d %d %d\n", maxSum, fst+1, lst+1);
}
return 0;
}