Blog of RuSun

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

P5685 [JSOI2013]快乐的 JYY

P5685 [JSOI2013]快乐的 JYY

要求公共回文串的组数。对两个串都建出 PAM 。同时 dfs ,这样每次得到的串都是相同的回文串,贡献 $s _ {A, i} s _ {B, i}$ 。

查看代码
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
#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);
}
typedef long long LL;
const int N = 5e4 + 10;
struct PAM
{
char str[N];
int n, cnt, last;
struct Node { int p, len, s, nxt[26]; } tr[N];
int get (int x, int t)
{
while (str[t - 1 - tr[x].len] != str[t]) x = tr[x].p;
return x;
}
void build()
{
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 = str[i] - 'A', p = get(last, i);
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;
}
++tr[last = tr[p].nxt[c]].s;
}
for (int i = cnt - 1; i > 1; --i)
tr[tr[i].p].s += tr[i].s;
tr[0].s = tr[1].s = 0;
}
} A, B;
LL ans;
void dfs (int x, int y)
{
ans += (LL)A.tr[x].s * B.tr[y].s;
for (int i = 0; i < 26; ++i)
if (A.tr[x].nxt[i] && B.tr[y].nxt[i])
dfs(A.tr[x].nxt[i], B.tr[y].nxt[i]);
}
int main ()
{
A.build(), B.build();
dfs(1, 1), dfs(0, 0);
write(ans);
return 0;
}