Blog of RuSun

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

P2414 [NOI2011] 阿狸的打字机

P2414 [NOI2011] 阿狸的打字机

根据题意建出 Trie 。考虑 AC 自动机上一点 $p$ ,其子树内任意一点 $s$ 一定出现了 $p$ 表示的串。考虑离线,对于每一个点回答这个点作为 $y$ 的答案,对于每个 $x$ ,从根节点到 $y$ 节点上每一个在 $x$ 子树内都有贡献。在树上遍历维护从根开始的链,每次查询子树和用树状数组维护。

查看代码
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <cstdio>
#include <queue>
#include <vector>
#define eb emplace_back
using namespace std;
template <class Type>
void read (Type &x)
{
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9')
if (c == '-') flag = true;
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 3) + (x << 1) + c - '0';
if (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)
{
if (x < 0) putchar('-'), x = ~x + 1;
if (x > 9) write(x / 10);
putchar('0' + x % 10);
}
const int N = 1e5 + 10;
vector <int> e[N];
struct Node { int p, fa, s[26]; } tr[N];
int n, m, tot, f[N], id[N], stmp, st[N], ed[N], ans[N];
struct Query { int id, x; Query (int _id, int _x) : id(_id), x(_x) { } };
vector <Query> g[N];
void add (int x, int k)
{
for (; x <= stmp; x += x & -x)
f[x] += k;
}
int query (int x)
{
int res = 0;
for (; x; x -= x & -x)
res += f[x];
return res;
}
void dfs1 (int u)
{
st[u] = ++stmp;
for (int v : e[u]) dfs1(v);
ed[u] = stmp;
}
void dfs2 (int u)
{
add(st[u], 1);
for (Query i : g[u])
ans[i.id] = query(ed[i.x]) - query(st[i.x] - 1);
for (int i = 0; i < 26; ++i)
if (tr[u].s[i] && tr[tr[u].s[i]].p == u) dfs2(tr[u].s[i]);
add(st[u], -1);
}
void build ()
{
queue <int> q;
for (int i = 0; i < 26; ++i)
if (tr[0].s[i]) q.push(tr[0].s[i]);
while (!q.empty())
{
int p = q.front(); q.pop();
for (int i = 0; i < 26; ++i)
{
int &s = tr[p].s[i];
if (!s) s = tr[tr[p].fa].s[i];
else { tr[s].fa = tr[tr[p].fa].s[i]; q.push(s); }
}
}
for (int i = 1; i <= tot; ++i) e[tr[i].fa].eb(i);
dfs1(0);
}
void init ()
{
int p = 0;
while (true)
{
char c = getchar();
if (c >= 'a' && c <= 'z')
{
int s = ++tot;
tr[p].s[c - 'a'] = s, tr[s].p = p;
p = s;
}
else if (c == 'B') p = tr[p].p;
else if (c == 'P') id[++n] = p;
else break;
}
}
int main ()
{
init(); build();
read(m);
for (int i = 1, x, y; i <= m; ++i)
{
read(x, y); x = id[x], y = id[y];
g[y].eb(i, x);
}
dfs2(0);
for (int i = 1; i <= m; ++i)
write(ans[i]), puts("");
return 0;
}