跳到正文

题解

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

_TwilightSnow_约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年10月4日
收录
2026年10月4日
更新
2026年11月22日
篇幅
约 5 分钟
获赞
1
题目
P15791

版本

  1. v1当前

这一题是不是太典了。

设 fif_i 表示 bb 已经加入 a1,a2,…aia_1, a_2,\dots a_i 时的最大得分,fstifst_i 表示 ii 第一次出现的位置,lstilst_i 表示 ii 上一次出现的位置,edied_i 表示 ii 最后一次出现的位置,stist_i 标记 ii 是否出现过。那么很容易推出转移方程式:

fi=max⁡j=0i−1{fj+∑x=1m[stx∧fstx≤j∧j<edx]×tx}. 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,对于每个位置 jj 存下该位置对应的 fj+∑x=1m[stx∧fstx≤j∧j<edx]×txf_j+\sum_{x=1}^m [st_x \land fst_x \le j \land j < ed_x] \times t_x,分析这个式子,发现加入一个新位置 ii,如果之前这个值出现过,那么它的贡献就是将 [lstai,i−1][lst_{a_i}, i - 1] 的位置的值全部加上了 tait_{a_i},实时更新 lstlst 和线段树即可。复杂度 O(nlog⁡n)O(n\log n)。

Code
C++
#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;
}
原文