题解:P15791 「1&0OI R1」空洞

· · 题解

这一题是不是太典了。

设 f_i 表示 b 已经加入 a_1, a_2,\dots a_i 时的最大得分,fst_i 表示 i 第一次出现的位置,lst_i 表示 i 上一次出现的位置,ed_i 表示 i 最后一次出现的位置,st_i 标记 i 是否出现过。那么很容易推出转移方程式:

f_i = \max_{j = 0}^{i - 1}\{ f_j+\sum_{x=1}^m [st_x \land fst_x \le j \land j < ed_x] \times t_x \}.

考虑线段树优化 DP,对于每个位置 j 存下该位置对应的 f_j+\sum_{x=1}^m [st_x \land fst_x \le j \land j < ed_x] \times t_x,分析这个式子,发现加入一个新位置 i,如果之前这个值出现过,那么它的贡献就是将 [lst_{a_i}, i - 1] 的位置的值全部加上了 t_{a_i},实时更新 lst 和线段树即可。复杂度 O(n\log n)。

:::success[Code]

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i, s, t) for (int i = s; i <= (int)t; i++)
#define pre(i, s, t) for (int i = s; i >= (int)t; i--)
namespace OI {
#ifdef _WIN32
#define getchar _getchar_nolock
#define putchar _putchar_nolock
#else 
#define getchar getchar_unlocked
#define putchar putchar_unlocked
#endif
    inline int rd() {
        int x = 0, f = 1; char c = getchar();
        while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); }
        while (isdigit(c)) x = x * 10 + c - '0', c = getchar();
        return x * f;
    }
    inline void wt(int x) {
        if (x < 0) putchar('-'), x = -x;
        if (x == 0) return putchar('0'), void();
        string str;
        while (x) str.push_back(x % 10 + '0'), x /= 10;
        reverse(begin(str), end(str));
        for (char &c : str) putchar(c);
    }
    inline void wt(string str) { for (char &c : str) putchar(c); }
}
using namespace OI;
#define ls u << 1
#define rs u << 1 | 1
#define mid (((l) + (r)) >> 1)
const int N = 5e5 + 2;
int n, m, lst[N], a[N], x[N], f[N], t[N << 2], tag[N << 2];
inline void pushup(int u) { t[u] = max(t[ls], t[rs]); }
inline void add(int u, int v) { t[u] += v, tag[u] += v; }
inline void pushdw(int u) { if (tag[u]) add(ls, tag[u]), add(rs, tag[u]), tag[u] = 0; }
void upd(int u, int l, int r, int ql, int qr, int v) {
    if (ql <= l && r <= qr) return add(u, v);
    pushdw(u);
    if (ql <= mid) upd(ls, l, mid, ql, qr, v);
    if (qr > mid) upd(rs, mid + 1, r, ql, qr, v);
    pushup(u);
}
int qry(int u, int l, int r, int ql, int qr) {
    if (ql <= l && r <= qr) return t[u];
    pushdw(u); int res = 0;
    if (ql <= mid) res = qry(ls, l, mid, ql, qr);
    if (qr > mid) res = max(res, qry(rs, mid + 1, r, ql, qr));
    return res;
}
signed main() {
    n = rd(), m = rd();
    rep(i, 1, n) a[i] = rd();
    rep(i, 1, m) x[i] = rd();
    rep(i, 1, n) {
        if (lst[a[i]]) upd(1, 0, n, lst[a[i]], i - 1, x[a[i]]);
        f[i] = qry(1, 0, n, 0, i - 1);
        upd(1, 0, n, i, i, f[i]), lst[a[i]] = i;
    }
    return wt(f[n]), 0;
}

:::