传送门
Luogu
解题思路
想要做这道题,只要会维护区间最大子段和就好了。
而这个可以用线段树维护模板点这里
对于重复的情况,我们可以对每一个位置记一个前驱表示和当前位置种类相同的前一个位置。
然后通过这个来消除贡献。
于是就做完了?
细节注意事项
- 咕咕咕
参考代码
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <ctime>
#define rg register
using namespace std;
template < typename T > inline void read(T& s) {
s = 0; int f = 0; char c = getchar();
while (!isdigit(c)) f |= (c == '-'), c = getchar();
while (isdigit(c)) s = s * 10 + (c ^ 48), c = getchar();
s = f ? -s : s;
}
typedef long long LL;
const int _ = 1000010;
int n, m, f[_], w[_], pre[_], las[_];
struct node { LL sum, L, R, mx; }t[_ << 2];
inline int lc(int rt) { return rt << 1; }
inline int rc(int rt) { return rt << 1 | 1; }
inline void pushup(int rt) {
t[rt].sum = t[lc(rt)].sum + t[rc(rt)].sum;
t[rt].L = max(t[lc(rt)].L, t[lc(rt)].sum + t[rc(rt)].L);
t[rt].R = max(t[rc(rt)].R, t[rc(rt)].sum + t[lc(rt)].R);
t[rt].mx = max(t[lc(rt)].R + t[rc(rt)].L, max(t[lc(rt)].mx, t[rc(rt)].mx));
}
inline void update(int id, LL v, int rt = 1, int l = 1, int r = n) {
if (l == r) { t[rt] = (node) { v, v, v, v }; return; }
int mid = (l + r) >> 1;
if (id <= mid) update(id, v, lc(rt), l, mid);
else update(id, v, rc(rt), mid + 1, r);
pushup(rt);
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.in", "r", stdin);
#endif
read(n), read(m);
for (rg int i = 1; i <= n; ++i) read(f[i]);
for (rg int i = 1; i <= m; ++i) read(w[i]);
for (rg int i = 1; i <= n; ++i)
pre[i] = las[f[i]], las[f[i]] = i;
LL ans = 0;
for (rg int i = 1; i <= n; ++i) {
if (pre[i]) update(pre[i], -w[f[i]]);
if (pre[pre[i]]) update(pre[pre[i]], 0);
update(i, (LL) w[f[i]]), ans = max(ans, t[1].mx);
}
printf("%lld\n", ans);
return 0;
}
完结撒花 \(qwq\)