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.
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).
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.
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
Case 1:
14 1 4
Case 2:
7 1 6
很明显是最长子序列问题。一开始我也是就这么写的。但是处理起来又貌似有点不一样。数组太大。总是Runtime Error (ACCESS_VIOLATION)。我于是百度了一下。借鉴别人借鉴的别人的。
http://blog.csdn.net/akof1314/article/details/4757021
自己Ac代码:
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<climits>
using namespace std;
#define N 11000
int a[N];
int main()
{
int t, i, k, n, max, x, temp, p1, p2, now;
scanf("%d", &t);
for(k = 1; k <= t; k++)
{
scanf("%d%d", &n, &temp);
x = p1 = p2 = 1;
max = now = temp;//初始化
for(i = 2; i <= n; i++)
{
scanf("%d", &temp);
if(now+temp < temp)//判断这个数前边的数是加还是不加,如果不加就把起始位置置为i
{
now = temp;
x = i;
}
else now += temp;
if(now > max)//记录当前最大值时的起始及结束位置坐标
{
p1 = x;
p2 = i;
max = now;
}
}
if(k != 1)
printf("\n");//格式控制,也可以由k是否等于n判断输出之后是否输出换行
printf("Case %d:\n", k);
printf("%d %d %d\n", max, p1, p2);
}
return 0;
}
IDEAS:
计算机,或者程序自身是有记忆功能的。当你处理每一步时,你都可以利用前边已经计算过的值或者结果处理你下一步如何操作。尤其是当数组很大,或者时间超限的时候。既可以减少运行内存还能降低运行时间。。你当然也可以选择继续没想法下去