HDU 1024 Max Sum Plus Plus【DP+优化时间复杂度】

Problem Description
Now I think you have got an AC in Ignatius.L's "Max Sum" problem. To be a brave ACMer, we always challenge ourselves to more difficult problems. Now you are faced with a more difficult problem.

Given a consecutive number sequence S 1, S 2, S 3, S 4 ... S x, ... S n (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ S x ≤ 32767). We define a function sum(i, j) = S i + ... + S j (1 ≤ i ≤ j ≤ n).

Now given an integer m (m > 0), your task is to find m pairs of i and j which make sum(i 1, j 1) + sum(i 2, j 2) + sum(i 3, j 3) + ... + sum(i m, j m) maximal (i x ≤ i y ≤ j x or i x ≤ j y ≤ j x is not allowed).

But I`m lazy, I don't want to write a special-judge module, so you don't have to output m pairs of i and j, just output the maximal summation of sum(i x, j x)(1 ≤ x ≤ m) instead. ^_^
 

 

Input
Each test case will begin with two integers m and n, followed by n integers S 1, S 2, S 3 ... S n.
Process to the end of file.
 

 

Output
Output the maximal summation described above in one line.
 

 

Sample Input
1 3 1 2 3

2 6 -1 4 -2 3 -2 3
 

 

Sample Output
6

8
Hint
Huge input, scanf and dynamic programming is recommended.
 

思路

思路很清晰,但是超时掉,寻找优化算法.

题意:是找K段序列和使他的和最大。

状态转移方程为:

f[i][j]表示连续j个数分成i段最大

           f[i-1][j-1]+a[i]    当i==j时

f[i][j]=

            max(f[i-1][k])   i-1=<k<=j-1

但是这样算法的时间复杂度达到O(n^3)会超时,因此再算出来 f[i][j]时就把最大的f[i][k]算出来,时间复杂度为O(n^2)

源码

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define INF 999999999
int a[1000023];
__int64 f[2][1000023];
int main()
{
    int i, j, n, m, k;
    while(scanf("%d%d", &m, &n)!=EOF)
    {
        //memset(a, 0, sizeof(a));
        //memset(f, 0, sizeof(f));  //这里会导致超时
        for(i=1; i<=n; i++)
        {
            scanf("%d", &a[i]);
            f[1][i]=f[0][i]=0;
        }
        int t=1;
        for(i=1; i<=m; i++)
        {
            f[t][i]=f[1-t][i-1]+a[i];
            f[1-t][i]=f[1-t][i-1]>f[1-t][i]?f[1-t][i-1]:f[1-t][i];
            for(j=i+1; j<=n; j++)
            {
                f[t][j]=(f[t][j-1]>f[1-t][j-1]?f[t][j-1]:f[1-t][j-1])+a[j];
                f[1-t][j]=f[1-t][j]>f[1-t][j-1]?f[1-t][j]:f[1-t][j-1];
            }
            t=1-t;
        }
        t=1-t;
        __int64 maxnum=-INF;
        for(i=m; i<=n; i++)
            maxnum=max(maxnum, f[t][i]);
        printf("%d\n", maxnum);
    }
}

 

你可能感兴趣的:(时间复杂度)