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
增加测试样例:
4 0 0 2 0 —— 2 1 3 6 2 7 -9 5 4 3 —— 12 1 6 4 0 0 -1 0 —— 0 1 1 7 -1 -2 -3 -2 -5 -1 -2 —— -1 1 1 6 -1 -2 -3 1 2 3 —— 6 4 6
C++实现:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
while(n--){
int num[100001];
int N;
cin >> N;
for(int k = 0;k < N;k++){ //数据存入数组
cin >> num[k];
}
int maximun = num[0];
int head,tail; //头节点与尾节点
int temp = 0; //中间调用模板
for(int i = 0;i < N;i++){ //num[i]作为序列首项
for(int j = i;j < N;j++){ //j = i
temp = temp + num[j];
if(maximun < temp){
maximun = temp;
head = i + 1;
tail = j + 1;
}
}
temp = 0;
}
int order = 1;
cout << "Case " << order << ":" <<endl;
cout << maximun << " " << head << " " << tail << endl;
order++;
}
return 0;
}
//这是两层嵌套循环列出所有可能,取出最大值
当然这个是超时的 >=->
不超时算法C++实现:
首先确定出
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int ordern = n; //换行输出参数
int order = 1; //换行输出参数
while(n--){
int num[100001];
int N;
cin >> N;
for(int k = 0;k < N;k++){ //数据存入数组
cin >> num[k];
}
int maximun = num[0]; //最大值初始化为num[0]
int head = 0,tail = 0; //头节点与尾节点
int temphead = 0; //头节点模板
int temp = 0; //最大值模板
for(int i = 0;i < N;i++){ //num[i]作为序列首项
/*
temp += num[i];
if(temp < 0){ //模板小于零的时候
temphead = i + 1; //重新设置头节点
temp = 0; //重新初始化模板为零
}
if(temp > maximun){ //如果模板值大于最大值就交换
maximun = temp;
head = temphead;
tail = i; //尾节点加一
}
*/
//注释部分与下面显示部分顺序不同结果也不同
//如果是上面注释部分的代码的化,temp的初始化必须放在一次循环的最末端
temp += num[i];
if(temp > maximun){ //如果模板值大于最大值就交换
maximun = temp;
head = temphead;
tail = i; //尾节点加一
}
if(temp < 0){ //模板小于零的时候
temphead = i + 1; //重新设置头节点
temp = 0; //重新初始化模板为零
}
}
cout << "Case " << order << ":" <<endl;
cout << maximun << " " << head + 1 << " " << tail + 1 << endl;
if( order < ordern ){
cout << endl;
}
order += 1;
}
return 0;
}