hdu 1003 MAX SUM——最大サブシーケンス解題報告

3520 ワード

原題:
Max Sum
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 282943    Accepted Submission(s): 67221
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
 

Author
Ignatius.L

直接暴力写的话,时间复杂度为O(n^2),会超时。

用DP的思想:若我们已经找到一个最大的子序列a,其中m为其中最后一个元素,那么在m之前的元素和一定大于零,(如果小于零,那么最大子序列应该更新为m),所以我们可以从0-n-1遍历元素位置,然后用flag_start和flag_end维护最大子序列的初始元素与末尾元素,用_max维护子序列和的最大值。

下面上代码:(不懂可以看注释)

#include
#include
#include
#include
using namespace std;
int a[100010];
int sum=0;
int _max=0x80000000,flag_start,flag_end,here_start,here_end;//0x80000000  16     int   
int main()
{
	int t,_case;
	cin>>t;
	int caseNum=0;
	while(t--)
	{
		caseNum++; 
		cin>>_case;
		memset(a,0,100010);//    
		sum=0;
		_max=0x80000000;
		flag_start=flag_end=here_start=0;
		here_end=-1;//      sum    a[0]  here_end++  ,       -1。
		for(int i=0;i<_case cin="">>a[i];
		}
		for(int i=0;i<_case if="" sum="a[i];" here_start="i;" here_end="i;" else="">_max)
			{
				_max=sum;
				flag_end=here_end;
				flag_start=here_start;
			}
		}
		printf("Case %d:
",caseNum); printf("%d %d %d
", _max,flag_start+1,flag_end+1); if(t) cout<