Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 52833 Accepted Submission(s): 11726
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
- /*
- 最大连续子序列 动态规划
- <a target=_blank href="http://acm.hdu.edu.cn/showproblem.php?pid=1231">http://acm.hdu.edu.cn/showproblem.php?pid=1231</a>
- 题意:给你一系列整数,选出所有 连续子序列 中 元素和最大 的一个子序列,
- 输出最大和、最大连续子序列的第一个和最后一个元素
- 思路见注释
- */
- #include <algorithm>
- #include <iostream>
- #include <iomanip>
- #include <fstream>
- #include <cstring>
- #include <string>
- #include <cstdio>
- #include <cmath>
- #include <stack>
- using namespace std;
- const int MAX=10005;
- int a[MAX];
- int main()
- {
- int n;
- int flag,max,sum,start,end,temp;
- int i,j;
- while(cin>>n && n){
- flag=0;
- for(i=0;i<n;i++)
- {
- scanf("%d",&a[i]);
- if(a[i]>=0)
- flag=1;
- }
- max=0;
- if(flag==0)
- {
- printf("%d %d %d\n",max,a[0],a[n-1]);
- continue;
- }
- else
- {
- sum=a[0];
- max=a[0];
- start=0;
- end=0;
- temp=0; //临时起点
- for(i=1;i<n;++i)
- {
- if(sum<0) { //如果前几项和小于0,就从新开始记录
- sum=0;
- temp=i; //刷新临时起点
- }
- sum+=a[i];
- if(sum>max){ //如果现在的sum大于原来的max,刷新数据
- max=sum;
- start=temp;
- end=i;
- }
- }
- printf("%d %d %d\n",max,a[start],a[end]);
- }
- }
- }
本文介绍了一种解决最大连续子序列求和问题的方法,并通过动态规划算法实现。该问题旨在从一组整数中找到连续子序列的最大和,同时输出该子序列的起始和结束位置。
321

被折叠的 条评论
为什么被折叠?



