HDU 1003-Max Sum(经典dp)

Max Sum

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


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

 

题目大意:在一个连续的序列中,求出和最大的子序列。

解题思路:我们从前往后遍历整个序列,用idx1表示子序列的头,idx2表示尾,sum1记录当前遍历到的项的前面的和(idx1~idx2-1),如果sum1<0就需要把idx1往后移一位,但是必须小于idx2,用一个sum2记录当前遍历所得到的最大和,然后用一个ans记录遍历过程的最优解即可,整个遍历过程有点类似于尺取法的思想.


AC代码:
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<queue>
#include<map>
#define bug printf("*********\n");
#define mem(a, b) memset(a, b, sizeof(a));
#define in1(n) scanf("%d" ,&n);
#define in2(a, b) scanf("%d%d", &a, &b);
#define out(n) printf("%d\n", n);
using namespace std;
typedef pair<long long, int> par;
const int mod = 1e9+7;
const int INF = -1e9;
const int N = 1000010;
const double pi = 3.1415926;

int T, n, a[100010];
int idx1, idx2, ans, sum1, sum2, l, r;

int main()
{
    int k = 1;
    scanf("%d", &T);
    int t = T;
    while(T --) {
        idx1 = idx2 = 1; //开始都指向序列的头
        l = r = 1;
        sum1 = sum2 = 0;
        ans = INF;
        scanf("%d", &n);
        for(int i = 1; i <= n; i ++)
            scanf("%d", &a[i]);
        while(idx2 <= n) {
            sum1 = sum2;
            sum2 += a[idx2];
            while(sum1 < 0 && idx1 < idx2) { //小于0的部分当然要去掉
                sum2 -= a[idx1];
                sum1 -= a[idx1];
                idx1 ++;
            }
            if(sum2 > ans) { //最优解
                l = idx1;
                r = idx2;
                ans = sum2;
            }
            idx2 ++;
        }
        printf("Case %d:\n", k ++);
        printf("%d %d %d\n", ans, l, r);
        if(k <= t) printf("\n"); //这里感觉是一大坑点,最后一组不输出
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/i_believe_cwj/article/details/80096827