#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
inline int read(){
int x = 0,f = 1;
char ch = getchar();
while(ch < '0' || ch > '9'){
if(ch == '-')
f = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9'){
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
char s[100005];
int m, x, y, tim, id[100005], ans[100005], cnt, tmp, tot, fa[100005], in[100005], out[100005], T[100005];
struct TRIE{
int d[27], fail;
}t[100005];
vector<int> d[100005];
vector< pair<int, int> > Q[100005];
void add(int x, int y){
for(; x <= tot; x += (x & (-x))) T[x] += y;
}
int query(int x){
int res = 0;
for(; x; x -= (x & (-x))) res += T[x];
return res;
}
void dfs(int x){
in[x] = ++tim;
for(int i = 0; i < d[x].size(); ++i){
dfs(d[x][i]);
}
out[x] = tim;
}
int main(){
scanf("%s", s + 1);
for(int i = 1; s[i]; ++i){
if(s[i] >= 'a' && s[i] <= 'z'){
if(!t[tmp].d[s[i] - 'a']){
t[tmp].d[s[i] - 'a'] = ++tot;
fa[tot] = tmp;
tmp = tot;
}
else tmp = t[tmp].d[s[i] - 'a'];
}
if(s[i] == 'P'){
id[++cnt] = tmp;
}
if(s[i] == 'B') tmp = fa[tmp];
}
queue<int> q;
for(int i = 0; i <= 25; ++i) if(t[0].d[i]) q.push(t[0].d[i]);
while(q.size()){
int x = q.front(); q.pop();
for(int i = 0; i <= 25; ++i){
if(t[x].d[i]){
q.push(t[x].d[i]);
t[t[x].d[i]].fail = t[t[x].fail].d[i];
}
else{
t[x].d[i] = t[t[x].fail].d[i];
}
}
}
for(int i = 1; i <= tot; ++i){
d[t[i].fail].push_back(i);
}
dfs(0);
m = read();
for(int i = 1; i <= m; ++i){
int p, q;
p = read(), q = read();
Q[q].push_back(make_pair(p, i));
}
tmp = 0; int now = 0;
for(int i = 1; s[i]; ++i){
if(s[i] >= 'a' && s[i] <= 'z'){
tmp = t[tmp].d[s[i] - 'a']; add(in[tmp], 1);
}
if(s[i] == 'B'){
add(in[tmp], -1);
tmp = fa[tmp];
}
if(s[i] == 'P'){
now++;
for(int j = 0; j < Q[now].size(); ++j){
ans[Q[now][j].second] = query(out[id[Q[now][j].first]]) - query(in[id[Q[now][j].first]] - 1);
}
}
}
for(int i = 1; i <= m; ++i) printf("%d\n", ans[i]);
return 0;
}
实现思路和一篇题解相似,但是找不出问题,请大佬帮忙看下/bx