题目要求
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
动态规划的入门题目,要求寻找最长链接的子序列。
从第一位找起,每次进行累加并于上一个进行对比选取最大值,记录当前的前后位置。
当sum累加到小于时清空sum,并改变起始位置。
sum += a[i]; //遍历i
if (sum > max)
{
max = sum;l = temp;r = i+1;
}
if (sum < 0)
{
sum = 0;temp = i+2;
}
完整代码
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<math.h>
using namespace std;
int main()
{
int j,i,k,n,m,t;
int a[100002];
scanf("%d",&t);
for (j=1;j<=t;j++)
{
scanf("%d",&n);
for (i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
int sum=0,max=-1001,l =0, r = 0, temp = 1;
for (i=0;i<n;i++)
{
sum += a[i];
if (sum > max)
{
max = sum;l = temp;r = i+1;
}
if (sum < 0)
{
sum = 0;temp = i+2;
}
}
printf("Case %d:\n%d %d %d\n",j,max,l,r);
if (j!=t)
{
printf("\n");
}
}
return 0;
}