Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

CF1107E Vasya and Binary String

LuoGu: CF1107E Vasya and Binary String

CF: E. Vasya and Binary String

考虑区间DP,但是发现由于中间删除后两边会合并,一般的区间DP难以维护。

注意到合并两个区间后,跨越两个区间产生贡献之可能是两边的数是一样的,所有将左区间一段最长的数相同的长度作为一维状态传给右区间。我们将开始的每种长度的贡献做一次背包,那么相同的一段长度越大则答案一定不会更劣。所以对于区间 $[l, r]$ ,在区间中找到一个 $i$ 可以接上 $l$ 及左侧的,将中间删除。

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long LL;
template <class Type>
void read (Type &x)
{
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9')
c == '-' && (flag = true);
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 1) + (x << 3) + c - '0';
flag && (x = ~x + 1);
}
template <class Type>
void write (Type x)
{
x < 0 && (putchar('-'), x = ~x + 1);
x > 9 && (write(x / 10), 0);
putchar('0' + x % 10);
}
const int N = 110;
char s[N];
int n;
LL w[N], f[N][N][N];
LL dfs (int l, int r, int k)
{
if (l > r)
return 0;
if (l == r)
return w[k];
LL &t = f[l][r][k];
if (t)
return t;
t = dfs(l + 1, r, 1) + w[k];
for (int i = l + 1; i <= r; i++)
s[i] == s[l] && (t = max(t, dfs(l + 1, i - 1, 1) + dfs(i, r, k + 1)));
return t;
}
int main ()
{
read(n);
scanf("%s", s + 1);
for (int i = 1; i <= n; i++)
{
read(w[i]);
for (int j = 0; j <= i - j; j++)
w[i] = max(w[i], w[j] + w[i - j]);
}
write(dfs(1, n, 1));
return 0;
}