杭电 hdoj 1003 动态规划 c语言题解

来源:互联网 发布:公务员培训老师知乎 编辑:程序博客网 时间:2024/05/17 04:58

Max Sum


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
25 6 -1 5 4 -77 0 6 -1 1 -6 7 -5
 

Sample Output
Case 1:14 1 4Case 2:7 1 6


很明显是一道动态规划的题目,还有种特别的方法,不过这种方法对于新手可能会比较难理解:


#include <stdio.h>#include <stdlib.h>int main(){    int t,i,n;    int temp,rear,head,j,maxrear,maxhead,sum,max;    scanf("%d",&t);    for(i=1;i<=t;i++){        scanf("%d",&n);        for(maxrear=0,maxhead=0,sum=max=-21000,j=1,head=1,rear=1;j<=n;j++){            scanf("%d",&temp);            //关键是判断当前的sum的值是否小于0            if(sum<0){                head=j;                rear=j;                sum=temp;            }            else {                sum+=temp;            }            if(sum>max){                max=sum;                maxhead=head;                maxrear=rear;            }            rear++;        }        printf("Case %d:\n",i);        printf("%d %d %d\n",max,maxhead,maxrear);        if(i!=t)printf("\n");    }    return 0;}

思路:将各个数依次相加,若和小于零则从当前加的数重新开始。

为什么?

因为题目中要求是连续的子序列,若是有一部分数的和小于零了,那这一部分的和肯定不可能包括在最大和里面,因为(前面的一部分和小于零的数)+(后面一部分加的数)肯定小于(后面一部分加的数),因而不可能是最优解,也就可以直接忽略(前面的一部分和小于零的数)。这是这种算法的关键所在。


需要注意的是若前几个数的和sum小于0时,应该从当前位置重新开始,如:1 -2 3  中1+(-2)小于0,则从3开始即在判断if(sum<0)语句中就令sum=temp相当于初始化,从当前位置重新开始。还有一点需要注意,就是sum和max的初始化一定要初始化一个很小的数,至于为什么大家可以自己看程序想想。


0 0