Max Sum II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2003 Accepted Submission(s): 618
Problem Description
Given a sequence a[1],a[2],a[3]......a[n], you can cut the sequence into one or more consecutive sub-sequences as you want, for example, you can cut them into (a[1]...a[j]), (a[k]...a[l]), (a[m]...a[n]),1≤j<k≤l<m≤n. Your job is to make the maximum sum using the least number of consecutive sub-sequences. For example, given (6,-1,0, -2, 3), the max sum in this sequence is 9, the number of sub-sequences is 2 not 3, they are(6), (3).
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<=1000000), 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 two integers, the number of consecutive sub-sequences and the max sum. Output a blank line between two cases.
Sample Input
2 2 6 -5 5 6 -1 0 -2 3
Sample Output
Case 1: 1 6 Case 2: 2 9
Author
Westwind Bolws@HDU
Source
问题链接:HDU3421 Max Sum II。
问题简述:整数序列分为几个子段,其各个子段和为最大。
问题分析:需要考虑0的情况,可能是单独的一个子段,也可能是一个子段中的一个元素。
程序说明:常规的处理,因为需要排除负数并且计数子段的数量,所有使用变量flag。
题记:(略)
AC的C++语言程序如下:
/* HDU3421 Max Sum II */
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int t, n, a;
scanf("%d", &t);
for(int i=1; i<=t; i++) {
int sum = 0, cnt = 0;
bool flag = true;
scanf("%d", &n);
for(int j=1; j<=n; j++) {
scanf("%d", &a);
if(a > 0) {
sum += a;
if(flag)
cnt++, flag = false;
} else if(a < 0)
flag = true;
}
if(i != 1)
printf("\n");
printf("Case %d:\n", i);
if(sum == 0)
printf("0 0\n");
else
printf("%d %d\n", cnt, sum);
}
return 0;
}