[Hdoj 1024] Max Sum Plus Plus

链接:http://acm.hdu.edu.cn/showproblem.php?pid=1024


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 S1, S2, S3, S4 … Sx, … Sn (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ Sx ≤ 32767). We define a function sum(i, j) = Si + … + Sj (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(i1, j1) + sum(i2, j2) + sum(i3, j3) + … + sum(im, jm) maximal (ix ≤ iy ≤ jx or ix ≤ jy ≤ jx 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(ix, jx)(1 ≤ x ≤ m) instead. ^_^
Input
Each test case will begin with two integers m and n, followed by n integers S1, S2, S3 … Sn.
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


分析:虽然题目没有提到m的范围,经测 n * m < 1e8 。定义状态state[i][j]表示 前j个数 取i段 且第j个数包含在最后一个区间中的区间最大和。接下来考虑状态转移,易得state[i][j]有两种转移,第一种是dp[i][j - 1]加上S[j]这个数,也就是只在最后一个区间末尾增加一个数S[j],另一种是由state[i - 1][k] k∈[1, j - 1]加上S[j], 在dp过程中取两者最优。则可写出转移方程:state[i][j] = max(state[i][j - 1] + S[j], max(state[i - 1][k], k∈[1, j - 1]) + S[j])。右边项“max(state[i - 1][k], k∈[1, j - 1])”在dp过程中一并维护即可使该题的时间复杂度降为O(n * m)。
因 n * m 过大,空间不足以开下二维dp数组,因此用滚动数组优化一下,最后考虑到32767 * n 有可能爆int,故dp数组用long long类型存储。


代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1LL << 61;
int s[1000001];
ll dp[2][1000001];
int main()
{
    ios::sync_with_stdio(0);
    int n, m;
    while (cin >> m >> n)
    {
        for (int i = 1; i <= n; i++)
            cin >> s[i];
        memset(dp, 0, sizeof dp);
        bool now = 0;
        for (int i = 1; i <= m; i++)
        {
            now = !now;
            ll maxs = dp[!now][i - 1];
            dp[now][i - 1] = -INF;
            for (int j = i; j <= n; j++)
            {
                dp[now][j] = max(dp[now][j - 1] + s[j], maxs + s[j]);
                maxs = max(maxs, dp[!now][j]);
            }
        }
        cout << *max_element(dp[now] + m, dp[now] + n + 1) << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/carrot_iw/article/details/81298395