没看懂其他题解为什么要建两个 /yun
思路
如果先是一串操作,后是一串询问,就是 的模板题。
可以建出一个 ,把所有加和删的字符串插进去。加串权值为 ,删串权值为 。查询的时候直接在 上走一遍这个串就可以统计出答案。
现在强制在线了,我们需要重新考虑。
每次插入一个串就必须要重构 树,这样肯定会超时。
很容易想到根号分治,每个 最多保存 个串的信息,最多会建出 个 。每次查询到每个 中查询并求和即可。这种做法需要卡常。
进一步地,我们考虑二进制分组。比如当前插入了 个串,,所以当前有 个 ,分别存了 个、 个、 个串。
在代码中体现为:每新插入一个串,先建出一个只存了当前串的新 ,如果存在另一个与当前 大小相同的 就不断合并。
每次查询在每个 查之后求和即可。
因为最多有 个 ,所以查询复杂度是 。
再来看插入,每个串一定只会经历 次合并,因为每次合并大小一定会 。所以每个串最多被重构了 次 指针。所以插入复杂度是 。
总复杂度 ,有个 的常数。
代码
#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 2e6 + 5, S = 26;
int n, type, lstans;
char s[N];
int idx, tot, rt[N], siz[N], ch[N][S], go[N][S], fa[N], ed[N], sum[N];
void ins(char *s, int val, int st) {
int u = st, len = strlen(s + 1);
for (int i = 1; i <= len; i++) {
int c = s[i] - 'a';
if (!ch[u][c]) ch[u][c] = ++idx;
u = ch[u][c];
}
ed[u] += val;
}
void build(int st) {
queue<int> q;
fa[st] = st;
for (int i = 0; i < S; i++) {
if (ch[st][i]) {
go[st][i] = ch[st][i];
fa[go[st][i]] = st;
q.push(go[st][i]);
}
else go[st][i] = st;
}
while (!q.empty()) {
int u = q.front();
q.pop();
sum[u] = sum[fa[u]] + ed[u];
for (int i = 0; i < S; i++) {
if (ch[u][i]) {
go[u][i] = ch[u][i];
fa[go[u][i]] = go[fa[u]][i];
q.push(go[u][i]);
}
else go[u][i] = go[fa[u]][i];
}
}
}
int merge(int p, int q) {
if (!p || !q) return p ^ q;
ed[p] += ed[q];
for (int i = 0; i < S; i++) ch[p][i] = merge(ch[p][i], ch[q][i]);
return p;
}
void upd(char *s, int val) {
rt[++tot] = ++idx;
siz[tot] = 1;
ins(s, val, rt[tot]);
while (siz[tot] == siz[tot - 1]) {
tot--;
siz[tot] += siz[tot + 1];
rt[tot] = merge(rt[tot], rt[tot + 1]);
}
build(rt[tot]);
}
int query(char *s, int st) {
int u = st, len = strlen(s + 1), res = 0;
for (int i = 1; i <= len; i++) {
int c = s[i] - 'a';
u = go[u][c];
res += sum[u];
}
return res;
}
int main() {
scanf("%d", &n);
while (n--) {
int op;
scanf("%d %s", &op, s + 1);
if (op == 1) upd(s, 1);
if (op == 2) upd(s, -1);
if (op == 3) {
int res = 0;
for (int i = 1; i <= tot; i++) res += query(s, rt[i]);
cout << res << endl;
lstans = res;
}
}
return 0;
}