这一题是不是太典了。
设 表示 已经加入 时的最大得分, 表示 第一次出现的位置, 表示 上一次出现的位置, 表示 最后一次出现的位置, 标记 是否出现过。那么很容易推出转移方程式:
考虑线段树优化 DP,对于每个位置 存下该位置对应的 ,分析这个式子,发现加入一个新位置 ,如果之前这个值出现过,那么它的贡献就是将 的位置的值全部加上了 ,实时更新 和线段树即可。复杂度 。
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;
}