Blog of RuSun

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

P4762 [CERC2014]Virus synthesis

P4762 [CERC2014]Virus synthesis

构造的方式一定反复加上若干字符求回文串。可以发现:奇数长度的回文串是不能通过一次求回文串操作得到的,即使其中可能包含了偶回文串可以更快的得到,但是也可以通过这个偶回文串构造出这个串:因此奇数长度的回文串只用于作为一个状态来构造偶数长度的回文串。对于偶数长度的回文串,考虑如何转移,对于一个回文串 $t$ ,两侧增加相同的字母得到 $v$ ,那么可以将 $t$ 增加一个字母再求回文串,有 $f _ v = f _ t + 1$ ;对于一个回文串 $v$ , 祖先上有一个串 $p$ 满足 $len _ p * 2 \le len _ v$ ,那么也可以增加若干个字符求回文串,即 $f _ v = f _ p + 1 + \frac {len _ v} 2 - len _ p$ 。为了保证转移顺序,可以 bfs 。

查看代码
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
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, class ...rest>
void read (Type &x, rest &...y) { read(x), read(y...); }
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 = 1e5 + 10;
char str[N];
int n, cnt, last, g[N], f[N];
struct Node { int p, len, nxt[4]; } tr[N];
int get (int x, int t)
{
while (str[t - 1 - tr[x].len] != str[t]) x = tr[x].p;
return x;
}
int main ()
{
int T; read(T);
while (T--)
{
scanf("%s", str + 1), str[0] = '$';
n = strlen(str + 1);
tr[0].p = 1, tr[1].len = -1;
last = 0, cnt = 2;
for (int i = 1; i <= n; ++i)
{
int c, p = get(last, i);
if (str[i] == 'A') c = 0;
else if (str[i] == 'T') c = 1;
else if (str[i] == 'C') c = 2;
else if (str[i] == 'G') c = 3;
if (!tr[p].nxt[c])
{
int q = cnt++;
tr[q].len = tr[p].len + 2;
tr[q].p = tr[get(tr[p].p, i)].nxt[c];
tr[p].nxt[c] = q;
if (tr[q].len <= 2) g[q] = tr[q].p;
else
{
int t = g[p];
while (str[i - 1 - tr[t].len] != str[i] || (tr[t].len + 2) * 2 > tr[q].len) t = tr[t].p;
g[q] = tr[t].nxt[c];
}
}
last = tr[p].nxt[c];
}
for (int i = 2; i < cnt; ++i) f[i] = tr[i].len;
queue <int> q;
q.push(0);
f[0] = 1;
int res = n;
while (!q.empty())
{
int t = q.front(); q.pop();
for (int i = 0; i < 4; ++i)
{
int v = tr[t].nxt[i];
if (!v) continue;
f[v] = min(f[t] + 1, f[g[v]] + 1 + tr[v].len / 2 - tr[g[v]].len);
res = min(res, f[v] + n - tr[v].len);
q.push(v);
}
}
for (int i = 0; i < cnt; ++i)
for (int j = 0; j < 4; ++j) tr[i].nxt[j] = 0;
write(res), puts("");
}
return 0;
}