SPOJ GSS3 (动态dp)

Posted zwfymqz

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SPOJ GSS3 (动态dp)相关的知识,希望对你有一定的参考价值。

题意

题目链接

Sol

这题可以动态dp做。

(f[i])表示以(i)为结尾的最大子段和,(g[i])表示(1-i)的最大子段和

那么

(f[i] = max(f[i - 1] + a[i], a[i]))

(g[i] = max(g[i - 1], f[i]))

发现只跟前一项有关,而且(g[i]从)f[i]$转移过来的那一项可以直接拆开

那么构造矩阵

[ egin{bmatrix} a_{i} & -infty & dots a_{i} \ a_{i}, & 0 & a_{i}\ -infty, & -infty & 0 \ end{bmatrix} ]

直接转移就行了

复杂度(O(nlogn * 27))

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1e6 + 10, INF = 1e9;
template<typename A, typename B> inline bool chmax(A &x, B y) {return x < y ? x = y, 1 : 0;}
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
struct Ma {
    int m[4][4];
    Ma() {
        memset(m, -0x3f, sizeof(m));
    }
    Ma operator * (const Ma &rhs) const {
        Ma ans;
        for(int i = 1; i <= 3; i++)
            for(int j = 1; j <= 3; j++)
                for(int k = 1; k <= 3; k++)
                    chmax(ans.m[i][j], m[i][k] + rhs.m[k][j]);
        return ans; 
    }
    void init(int v) {
        m[1][1] = v; m[1][2] = -INF; m[1][3] = v;
        m[2][1] = v; m[2][2] = 0;    m[2][3] = v;
        m[3][1] = -INF; m[3][2] = -INF; m[3][3] = 0;
    }
}m[MAXN];
int N, M, a[MAXN];
#define ls k << 1
#define rs k << 1 | 1
void update(int k) {
    m[k] = m[ls] * m[rs];
}
void Build(int k, int l, int r) {
    if(l == r) {m[k].init(a[l]); return ;}
    int mid = l + r >> 1;
    Build(ls, l, mid); Build(rs, mid + 1, r);
    update(k);
}
void Modify(int k, int l, int r, int p, int v) {
    if(l == r) {m[k].init(v); return ;}
    int mid = l + r >> 1;
    if(p <= mid) Modify(ls, l, mid, p, v);
    else Modify(rs, mid + 1, r, p, v);
    update(k);
}
Ma Query(int k, int l, int r, int ql, int qr) {
    if(ql <= l && r <= qr) 
        return m[k];
    int mid = l + r >> 1;
    if(ql > mid) return Query(rs, mid + 1, r, ql, qr);
    else if(qr <= mid) return Query(ls, l, mid, ql, qr);
    else return (Query(ls, l, mid, ql, qr) * Query(rs, mid + 1, r, ql, qr));
}
int main() {
    N = read();
    for(int i = 1; i <= N; i++) a[i] = read();
    Build(1, 1, N);
    M = read();
    while(M--) {
        int opt = read(), x = read(), y = read();
        if(opt == 0) Modify(1, 1, N, x, y);
        else {
            Ma ans = Query(1, 1, N, x, y);
            printf("%d
", max(ans.m[2][1], ans.m[2][3]));
        }
    }
    return 0;
}
/*
4
-1 -2 -3 -4
2
1 1 4
1 1 2
*/

以上是关于SPOJ GSS3 (动态dp)的主要内容,如果未能解决你的问题,请参考以下文章

SPOJ GSS3 单点修改+区间最大子段和

SPOJ GSS3 线段树系列1

SP1716 GSS3 - Can you answer these queries III - 动态dp,线段树

SPOJ - GSS1&&GSS3

Spoj GSS3 - Can you answer these queries III

SPOJ GSS3 Can you answer these queries III