HDU 1003 Max Sum

来源:互联网 发布:大神小的知错了微盘 编辑:程序博客网 时间:2024/06/06 15:54

简单dp入门
其实感觉这题贪心可写,分治可写

题目:
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

思路:简单的dp,然而我开的数组明显比别人多一个,甚至有些人没开数组。。
我的想法是先开一个数组d[maxn] 保存以i为结尾的最大的连续和的值,而sti[i]保存这些值以哪一个下标为开始。
temp 是当前下标为i的值
故有d[i] = max(temp, temp + d[i-1]); 当temp值比较大时,sti[i] = i,另外一种情况时, sti[i] = sti[i-1]

代码:

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;#define maxn 100005#define inf 0x3f3f3f3fint d[maxn];int sti[maxn];int main(){    //freopen("D://in.txt","r",stdin);    int t;    scanf("%d",&t);    for(int kase = 1; kase <= t; kase ++)    {        int n;        scanf("%d",&n);        int temp;        scanf("%d",&temp);        d[0] = temp;        for(int i = 1; i < n ; i++)        {            scanf("%d",&temp);            d[i] = max(d[i-1] + temp, temp);            if(d[i-1] + temp <= temp)                sti[i] = i;            else                sti[i] = sti[i-1];        }        int ans = -inf;        int ansj = -1;        int ansi = -1;        for(int i = 0; i < n ; i++)        {            if(ans < d[i])            {                ans = d[i];                ansj = i;                ansi = sti[i];            }        }        if(kase != 1)            printf("\n");        printf("Case %d:\n",kase);        printf("%d %d %d\n",ans,ansi+1,ansj+1);    }    return 0;}
0 0
原创粉丝点击