您的位置:首页 > 编程语言 > PHP开发

DP专题2 HDOJ 1003 Max Sum

2012-07-20 15:23 381 查看
传送门: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): 81597    Accepted Submission(s): 18767

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.

[align=left]Input[/align]
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).

 
[align=left]Output[/align]
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.

 
[align=left]Sample Input[/align]

2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5

 
[align=left]Sample Output[/align]

Case 1:
14 1 4

Case 2:
7 1 6

 
[align=left]Author[/align]
Ignatius.L
 

    问题描述:取一个数组中连续的m个数,使其总和最大

    算法分析:DP思路,此题不仅要求输出最大的和而且要求输出他的起始位置和结束位置。我的思路是定义状态temp[]数组,temp[i]表示以i作为尾巴的总和最大的连续数的和,这里的temp[i]可能是i一个数字,也可能是i加上i前面的连续几个数字。

    实现: 首先temp[1] = input[1] ,px[1] = 1 py[1] = 1 对于temp[i](i >= 2) ,如果temp[i-1]>=0 在i-1的基础上加上i必然是temp[i]的最大值,则temp[i] = temp[i-1] + input[i] ,px[i] = px[i-1]  py[i] = i ;如果temp[i-1] < 0 则temp[i] 只能等于input[i]否则会更小。

    所以temp[i] = input[i] + temp[i-1]>=0?temp[i-1]:0 ; 即是新的状态方程

    代码如下:

   

/*Memory: 1768 KB   Time: 31 MS
Language: GCC   Result: Accepted

This source is shared by hust_lcl
*/
#include <stdio.h>
#include <stdlib.h>
int input[100010];
int temp[100010];
int px[100010];
int py[100010];
int main()
{
int n , m , i , flag , k = 1 , j;
scanf("%d",&n);
while(n--)
{
scanf("%d",&m);
for(i = 1 ; i <= m ; i ++)
scanf("%d",&input[i]);
printf("Case %d:\n",k++);
temp[1] = input[1];
px[1] = 1;
py[1] = 1;
for(i = 2 ; i <= m ; i ++ )
{
if(temp[i-1]>=0)
{
temp[i] = input[i] + temp[i-1];
px[i] = px[i-1];
py[i] = i;
}
else
{
temp[i] = input[i];
px[i] = i ;
py[i] = i;
}
}
flag = temp[1];
j = 1;
for(i = 1 ; i <= m ; i++)
if(temp[i] > flag)
{
flag = temp[i];
j = i;
}
printf("%d %d %d\n",flag, px[j],py[j]);
if(n>0) printf("\n");
}
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息