码迷,mamicode.com
首页 > 其他好文 > 详细

HDU1003_Max Sum

时间:2014-10-17 22:00:36      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:des   style   io   os   ar   java   for   sp   div   

Max Sum


Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 149069    Accepted Submission(s): 34828

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
 
Author

Ignatius.L

题目大意:求使连续子序列的和最大的第一元素,最后一个元素位置,和子序列

的和

思路:动态规划的方法,主要是找到状态转移方程。将之前累加和加上当前值

与当前值做比较, 如果将之前累加和加上当前值>当前值,那么加上当前值,

最后一个元素位置变为i,如果将之前累加和加上当前值<当前值,那么sum[i] 

a[i],并且改变第一元素位置为i,最后元素位置为i。具体看代码。

状态转移方程:sum[i]=max(sum[i-1]+a[i],a[i]);


# include<stdio.h>
# include<string.h>
int num[100010];

int main()
{
    int i,T,N,sum,max,t,a,b,a1,b1;
    scanf("%d",&T);
    t = 1;
    while(T--)
    {    
        scanf("%d",&N);
        memset(num,0,sizeof(num));
        for(i=0;i<N;i++)
            scanf("%d",&num[i]);
        max  = sum = num[0];
        a1 = b1 = a = b = 1;
        for(i=1;i<N;i++)
        {
            if(num[i]>sum+num[i])
            {
                sum = num[i];
                a = i+1;
                b = i+1;
            }
            else
            {
                sum += num[i];
                b = i+1;
            }
            if(max<sum)
            {
                max = sum;
                a1 = a;
                b1 = b;
            }    
        }
        printf("Case %d:\n%d %d %d\n",t++,max,a1,b1);
        if(T)
            printf("\n");
    }
    
    return 0;
}


HDU1003_Max Sum

标签:des   style   io   os   ar   java   for   sp   div   

原文地址:http://blog.csdn.net/lianai911/article/details/40191503

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!