CodeForces 547E Mike and Friends
思路
类比 洛谷 P2414 / LOJ 2444 「NOI2011」阿狸的打字机 。如果做过那题,那这题就很简单了。
首先把 \([l,r]\) 拆成 \([1,l-1]\) 和 \([1,r]\)。设 \(a_i\) 为第 \(i\) 个字符串在 AC 自动机上的终止结点。仍然考虑在 AC 自动机上匹配的过程,\(x\) 在 \(y\) 中出现的次数就相当于在 Trie 树上 \(a_y\) 到根结点的链上,每个结点都不断跳 \(\mathrm{fail}\),有多少个结点是 \(a_x\),也就是在 \(\mathrm{fail}\) 树上有多少个结点在 \(a_x\) 的子树内。
于是直接上树状数组,单点加/区间求和即可。具体地,遍历到第 \(i\) 个字符串时,将 \(a_i\) 到根结点的链上的所有点都 \(+1\)。然后处理 \([1,i]\) 的询问,就是查询 \(a_k\) 在 \(\mathrm{fail}\) 树中的子树和。
代码
code
/*
p_b_p_b txdy
AThousandMoon txdy
AThousandSuns txdy
hxy txdy
*/
#include <bits/stdc++.h>
#define pb push_back
#define fst first
#define scd second
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
const int maxn = 200100;
const int maxm = 500100;
int n, m, head[maxn], len, st[maxn], ed[maxn], times;
int ans[maxm], c[maxn], idx[maxn];
char s[maxn];
struct node {
int x, op, id;
node() {}
node(int a, int b, int c) : x(a), op(b), id(c) {}
};
vector<node> qq[maxn];
struct edge {
int to, next;
} edges[maxn << 1];
void add_edge(int u, int v) {
edges[++len].to = v;
edges[len].next = head[u];
head[u] = len;
}
inline int lowbit(int x) {
return x & (-x);
}
inline void update(int x, int d) {
for (int i = x; i <= times; i += lowbit(i)) {
c[i] += d;
}
}
inline int query(int x) {
int res = 0;
for (int i = x; i; i -= lowbit(i)) {
res += c[i];
}
return res;
}
struct AC {
int ch[maxn][26], tot, fail[maxn], fa[maxn];
void insert(char *s, int id) {
int p = 0;
for (int i = 0; s[i]; ++i) {
if (!ch[p][s[i] - 'a']) {
ch[p][s[i] - 'a'] = ++tot;
fa[tot] = p;
}
p = ch[p][s[i] - 'a'];
}
idx[id] = p;
}
void build() {
queue<int> q;
for (int i = 0; i < 26; ++i) {
if (ch[0][i]) {
q.push(ch[0][i]);
}
}
while (q.size()) {
int u = q.front();
q.pop();
for (int i = 0; i < 26; ++i) {
if (ch[u][i]) {
fail[ch[u][i]] = ch[fail[u]][i];
q.push(ch[u][i]);
} else {
ch[u][i] = ch[fail[u]][i];
}
}
}
for (int i = 1; i <= tot; ++i) {
add_edge(fail[i], i);
}
}
void dfs(int u) {
st[u] = ++times;
for (int i = head[u]; i; i = edges[i].next) {
int v = edges[i].to;
dfs(v);
}
ed[u] = times;
}
} ac;
void solve() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i) {
scanf("%s", s);
ac.insert(s, i);
}
ac.build();
ac.dfs(0);
for (int i = 1, l, r, x; i <= m; ++i) {
scanf("%d%d%d", &l, &r, &x);
if (l > 1) {
qq[l - 1].pb(node(x, -1, i));
}
qq[r].pb(node(x, 1, i));
}
for (int i = 1; i <= n; ++i) {
// printf("i: %d\n", i);
for (int u = idx[i]; u; u = ac.fa[u]) {
// printf(" u: %d\n", u);
update(st[u], 1);
}
for (node p : qq[i]) {
ans[p.id] += p.op * (query(ed[idx[p.x]]) - query(st[idx[p.x]] - 1));
}
}
for (int i = 1; i <= m; ++i) {
printf("%d\n", ans[i]);
}
}
int main() {
int T = 1;
// scanf("%d", &T);
while (T--) {
solve();
}
return 0;
}