HDU 1003 解题报告
2014-05-24 19:09
507 查看
Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 137277 Accepted Submission(s): 31816
[align=left]Problem Description[/align]
Given a sequence a[1],a[2],a[3]......a
, 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.
[align=left]Input[/align]
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).
[align=left]Output[/align]
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.
[align=left]Sample Input[/align]
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
[align=left]Sample Output[/align]
Case 1:
14 1 4
Case 2:
7 1 6
分析:典型的求最大子序列和的问题,但是又有一些变化,需要知道当求得最大和时,子序列在元序列中的开始位置和结束位置。
首先,考虑暴力的方法,遍历整个序列,假定开始位置,然后去求当前开始位置下,任意结束位置的序列和,比较出最大的序列和即可。这样,时间复杂度为O(n^2)
进一步考虑,假设已经得到最大和的自序列,那么之所以这个自 序列不包含前面的几个或者后面几个元素的原因,就是因为前面(或者后面)连续几个元素的和是负数。这样,考虑子序列的结束位置,遍历0...n-1,假设当前位置为结束位置,那么如果以前面一个位置为结束的最大子序列和为负数时,只包含当前位置元素的子序列就是以当前位置结束的子序列的最大值;否则,以前面一个位置为结束的最大子序列和加上当前元素就是以当前位置结束的子序列的最大值。这样,按顺序遍历一遍,就可以得到以每个位置为结束位置的最大子序列的和,其中最大的就是整个序列最大子序列的和,时间复杂度O(n)。
代码:
#include<stdio.h> int main(){ int t, n, caseNum, maxSum, maxHere, beginMax, endMax, beginHere, endHere; int a[100002]; scanf("%d", &t); caseNum = 0; while(t--){ caseNum++; scanf("%d", &n); for(int i=0; i<n; i++){ scanf("%d", &a[i]); } maxSum = -2147483647-1; maxHere = 0; beginMax = 0; endMax = 0; beginHere = 0; endHere = -1; for(int i=0; i<n; i++){ if(maxHere<0){ maxHere=a[i]; beginHere = i; endHere = i; } else { maxHere+=a[i]; endHere++; } if(maxHere>maxSum){ maxSum = maxHere; beginMax = beginHere; endMax = endHere; } } printf("Case %d:\n", caseNum); printf("%d %d %d\n", maxSum, beginMax+1, endMax+1); if(t){ printf("\n"); } } }
相关文章推荐
- 坐标序列hdu 1003 解题报告 ---- Max Sum
- BestCoder9 1003 Revenge of kNN(hdu 4995) 解题报告
- HDU 1003 Max Sum 解题报告
- HDU 1003 解题报告
- hdu1003 Max Sum 解题报告
- hdu 1003 解题报告
- BestCoder11(Div2) 1003 Boring count (hdu 5056) 解题报告
- hdu 1003 解题报告 ---- Max Sum
- HDU解题报告--1003
- hdu 1003 Max Sum 解题报告
- hdu 2139解题报告
- hdu 1004解题报告
- hdu 1019解题报告
- HDU 2469 Fire-control System解题报告
- The sum problem(hdu 2058)解题报告
- HDU 1158 Emloyment Planning 解题报告
- HDU DIY Contest 【动态规划专题训练】JSU_ACM_第二小组解题报告
- pku 1003解题报告
- 2010 哈尔滨网络预选赛 1003解题报告
- POJ 1003(Hangover 简单数学) 解题报告