@Chilling
2016-08-19T18:58:13.000000Z
字数 1534
阅读 1159
DP
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
题意: t组数据,每组输入n再输入n个数,求最大连续子序列和,以及子序列的开头和结尾。
分析:若前面数的和大于等于0,那么现在这个数加上前面数的和肯定比自己本身更大或者等于本身,因此连续的子序列就要加上现在这个数,否则就不加。
sum[i]是以第i个数结尾的最大子序列的和,a[i]是原数组。
状态转移方程为:sum[i] = max{sum[i-1] + a[i], a[i]};
并且这道题需要找出序列的开头和结尾的位置,结尾的位置我们知道,因为已知以第i个数结尾最大的子序列和。问题是要找到开头。我们用数组st[i]存开头,如果前面序列的和大于0了,那么现在这个数还是纳入前面那个序列当中,所以st[i]=st[i-1],否则它这个序列就以自己开头,因此st[i]=i。
#include<stdio.h>
#include<string.h>
int main()
{
int t,n,i,a[111111],max,st[111111],e,tt=0;
scanf("%d",&t);
int sb=t;
while(t--)
{
tt++;
memset(st,0,sizeof(st));
memset(a,0,sizeof(a));
max=-99999999;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
st[0]=0;
for(i=1;i<n;i++)
{
if(a[i-1]>=0)
{
a[i]+=a[i-1];
st[i]=st[i-1];
}
else
st[i]=i;
}
for(i=0;i<n;i++)
if(a[i]>max)
{
max=a[i];
e=i;
}
printf("Case %d:\n%d %d %d\n",tt,max,st[e]+1,e+1);
if(tt!=sb)
printf("\n");
}
return 0;
}