[关闭]
@Chilling 2016-08-19T18:58:13.000000Z 字数 1534 阅读 1149

HDU-1003: Max Sum(最大连续子序列和)

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。


  1. #include<stdio.h>
  2. #include<string.h>
  3. int main()
  4. {
  5. int t,n,i,a[111111],max,st[111111],e,tt=0;
  6. scanf("%d",&t);
  7. int sb=t;
  8. while(t--)
  9. {
  10. tt++;
  11. memset(st,0,sizeof(st));
  12. memset(a,0,sizeof(a));
  13. max=-99999999;
  14. scanf("%d",&n);
  15. for(i=0;i<n;i++)
  16. scanf("%d",&a[i]);
  17. st[0]=0;
  18. for(i=1;i<n;i++)
  19. {
  20. if(a[i-1]>=0)
  21. {
  22. a[i]+=a[i-1];
  23. st[i]=st[i-1];
  24. }
  25. else
  26. st[i]=i;
  27. }
  28. for(i=0;i<n;i++)
  29. if(a[i]>max)
  30. {
  31. max=a[i];
  32. e=i;
  33. }
  34. printf("Case %d:\n%d %d %d\n",tt,max,st[e]+1,e+1);
  35. if(tt!=sb)
  36. printf("\n");
  37. }
  38. return 0;
  39. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注