经典动态规划问题——最大子段和问题

xiaoxiao2021-02-28  87

hud1003

问题描述

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.

 

问题分析:

这是一道经典的动态规划问题,动态规划是常见的算法题目,但是这道题国语经典,所以难度也不是特别的大,下来我来展示求解过程:

dp作为动态规划数组,dp[i]表示以i结尾的最大最大子段和。

动态规划方程为:dp[i]=maxdp[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; }

转载请注明原文地址: https://www.6miu.com/read-22950.html

最新回复(0)