G - 7
Time limit 1000 ms
Memory limit 32768 kB
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
问题链接:G - 7
问题简述:
输入T,代表有多少组数组
再输入n,代表这一组有多少个数据
求最大连续子序列和,以及首尾数据的位置
问题分析:
我们来看sample input
(5) 6 -1 5 4 -7
sample output
14 1 4
最大连续子序列和自然就是6+(-1)+5+4=14,首尾数据是第一位(6)和第四位(4)
核心是定义一个sum进行累加,用数组输入数据,定义一个maxn存放暂时符合要求的sum,若sum大于maxn就交换同时把尾位置定在这,若sum<0则把sum初始化为0重新开始累加,并把首位置定义在这个数的下一位(因为这个数之前的已经不可能是最大连续子序列和,可以理解为已经把前面的数筛选掉了)
程序说明:
num数组用于数据
maxn用于存放暂时符合要求的sum
sum用于累加(初始化值为0)
start和end用于标记开头和结尾(初始化值为0)
flag用于定义开头,因为i+1才是现在的那个数,而开头要定在下一个数,如果下一个数sum>maxn就把开头定在那里,所以是i+2(初始化值为1)
最后按格式输出,记得加endl即可
AC通过的C语言程序如下:
#include <iostream>
using namespace std;
int main()
{
int n,m,j,i;
int num[100002];
cin >> n;
for ( j = 1;j<= n;j++)
{
int maxn=-1000,sum=0,start=0,end=0,flag=1;
cin >> m;
for ( i = 0;i < m;i++)
{
cin >> num[i];
}
for ( i = 0;i < m;i++)
{
sum += num[i];
if (maxn < sum)
{
maxn = sum;
start=flag;
end = i+1;
}
if (sum < 0)
{
sum = 0;
flag = i + 2;
}
}
printf("Case %d:\n%d %d %d\n", j, maxn, start, end);
if (j != n) cout << endl;
}
}