您的位置:首页 > 其它

HDU 1003 Max Sum

2015-10-29 17:33 281 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1003

Max Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 188128    Accepted Submission(s): 43836

Problem Description

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.

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

Recommend

问题: 给定n个整数(可能为负数)组成的序列a[1],a[2],a[3],…,a
,求该序列如a[i]+a[i+1]+…+a[j]的子段和的最大值。当所给的整均为负数时定义子段和为0,依此定义,所求的最优值为: Max{0,a[i]+a[i+1]+…+a[j]},1<=i<=j<=n 例如,当(a[1],a[2],a[3],a[4],a[5],a[6])=(-2,11,-4,13,-5,-2)时,最大子段和为20。

最大子段和是动态规划中的一种。

若记b[j]=max(a[i]+a[i+1]+...+a[j]),其中1<=i<=j,并且1<=j<=n。则所求的最大子段和为max b[j],1<=j<=n。

由b[j]的定义可易知,当b[j-1]>0时b[j]=b[j-1]+a[j],否则b[j]=a[j]。故b[j]的动态规划递归式为:

b[j]=max(b[j-1]+a[j],a[j]),1<=j<=n。

------以上来自百度百科

另外需要注意的是起始位置的确定,当取b[j]=a[j]时要更新起始位置。

附上AC代码:

#include <iostream>
#include <cstdio>
#include <string>
#include <cmath>
#include <iomanip>
#include <ctime>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <deque>
//#pragma comment(linker, "/STACK:102400000, 102400000")
using namespace std;
typedef long long ll;
const double pi = acos(-1.0);
const double e = exp(1.0);
const double eps = 1e-8;
int n, num;

int main(){
ios::sync_with_stdio(false);
short T, cas=0;
scanf("%hd", &T);
while (T--){
scanf("%d", &n);
int maxsum=-1000, x=1, l, r=1, sum=0;
for (int i=1; i<=n; i++){
scanf("%d", &num);
if (sum >= 0)
sum += num;
else
sum=num, x=i;
if (sum > maxsum)
maxsum=sum, l=x, r=i;
}
cas++;
printf("Case %hd:\n%d %d %d\n", cas, maxsum, l, r);
if (0 != T)
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hdu 最大子段和