经典动态规划问题——最大子段和问题
2017-07-10 12:10
483 查看
hud1003
问题描述
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.
问题分析:
这是一道经典的动态规划问题,动态规划是常见的算法题目,但是这道题国语经典,所以难度也不是特别的大,下来我来展示求解过程:以dp作为动态规划数组,dp[i]表示以i结尾的最大最大子段和。
动态规划方程为:dp[i]=max(dp[i-1]+A[i],A[i])
源代码如下:
#include<iostream>
#include<cstdio>
#define maxn 100010
#define INF 0x7fffffff
using namespace std;
int A[maxn],dp[maxn],L[maxn],R[maxn];//L和R分别记录左起点和右起点
int N;
int main(){
int T;
cin>>T;
for(int kase=1;kase<=T;kase++){
cin>>N;
for(int i=0;i<N;i++)
scanf("%d",A+i);
dp[0]=A[0];L[0]=R[0]=0;
for(int i=1;i<N;i++){
if(dp[i-1]<0) L[i]=R[i]=i,dp[i]=A[i];
else L[i]=L[i-1],R[i]=i,dp[i]=dp[i-1]+A[i];
}
int l,r,Max=-INF;
for(int i=0;i<N;i++)
if(dp[i]>Max) Max=dp[i],l=L[i],r=R[i];
printf("Case %d:\n%d %d %d\n",kase,Max,l+1,r+1);
if(kase<T) printf("\n");
}
return 0;
}
相关文章推荐
- 动态规划经典问题03:数组中最大的数对差(或最小的数对差)
- 动态规划之最大子段和问题
- 阿里云笔试题:最大子段和问题的动态规划解法
- HDU 1024:Max Sum Plus Plus 经典动态规划之最大M子段和
- 最大子段和问题的动态规划解法
- 动态规划1:最大子段和问题到最大子矩阵问题(一):最大子段和问题详谈
- 动态规划之最大子段和问题
- 动态规划之最大子段和问题总结
- 动态规划2:最大子段和问题到最大子矩阵问题(二):最大n子段和问题详谈
- HDU 1024:Max Sum Plus Plus 经典动态规划之最大M子段和
- 动态规划之最大子段和问题
- 动态规划之最大子段和问题
- 阿里云笔试题:最大子段和问题的动态规划解法
- 动态规划3:最大子段和问题到最大子矩阵问题(三):初探最大子矩阵之和问题
- 51nod(动态规划入门---最大子段问题)
- 动态规划问题-DP 最大子段和O(n)解决方法
- 动态规划 最大子段和问题
- 经典动态规划——HDU1024 m段子段和的最大值
- 动态规划--最大子段和升级 最大矩阵和 hd1081
- hdu 1003 Max Sum(动态规划求一维最大子段和)