1 #include<cstdio>
2 #include<iostream>
3 #include<cmath>
4 #include<cstring>
5 #include<algorithm>
6 #include<vector>
7 #define lowbit(x) ((x)&(-(x)))
8 using namespace std;
9 char ch;
10 bool ok;
11 void read(int &x){
12 for (ok=0,ch=getchar();!isdigit(ch);ch=getchar()) if (ch==‘-‘) ok=1;
13 for (x=0;isdigit(ch);x=x*10+ch-‘0‘,ch=getchar());
14 if (ok) x=-x;
15 }
16 const int maxn=100005;
17 char s[maxn];
18 int len,q,x,y,idx,pos[maxn],num[maxn],ans[maxn];
19 typedef pair<int,int> PII;
20 vector<PII> querys[maxn];
21 struct Bit{
22 int n,val[maxn];
23 void init(int x){n=x;}
24 void modify(int x,int v){for (;x<=n;x+=lowbit(x)) val[x]+=v;}
25 int query(int x){
26 int res=0;
27 for (;x;x-=lowbit(x)) res+=val[x];
28 return res;
29 }
30 int query(int l,int r){return query(r)-query(l-1);}
31 }bit;
32 struct Graph{
33 int tot,now[maxn],son[maxn],pre[maxn],idx,dfn[maxn],last[maxn];
34 void put(int a,int b){pre[++tot]=now[a],now[a]=tot,son[tot]=b;}
35 void dfs(int u){
36 dfn[u]=++idx;
37 for (int p=now[u],v=son[p];p;p=pre[p],v=son[p]) dfs(v);
38 last[u]=idx;
39 }
40 void init(){dfs(0),bit.init(idx);}
41 void change(int u,int v){bit.modify(dfn[u],v);}
42 int query(int u){return bit.query(dfn[u],last[u]);}
43 }G;
44 struct trie{
45 int tot,son[maxn][26],fai[maxn],fa[maxn];
46 int head,tail,que[maxn];
47 void build_fai(){
48 head=0,tail=1,que[1]=0,fai[0]=-1;
49 while (head<tail){
50 int u=que[++head];
51 for (int ch=0,v=son[u][ch],t;ch<26;v=son[u][++ch]) if (v){
52 que[++tail]=v;
53 for (t=fai[u];t>=0&&!son[t][ch];t=fai[t]);
54 if (t>=0) fai[v]=son[t][ch]; else fai[v]=0;
55 }
56 }
57 }
58 void init(){
59 int p=0;
60 for (int i=1;i<=len;i++)
61 if (s[i]==‘P‘) pos[p]=++idx,num[idx]=p;
62 else if (s[i]==‘B‘) p=fa[p];
63 else{
64 if (!son[p][s[i]-‘a‘]) son[p][s[i]-‘a‘]=++tot,fa[tot]=p;
65 p=son[p][s[i]-‘a‘];
66 }
67 build_fai();
68 for (int i=1;i<=tot;i++) G.put(fai[i],i);
69 G.init();
70 }
71 void solve(){
72 int p=0; G.change(p,1);
73 for (int i=1;i<=len;i++)
74 if (s[i]==‘P‘){
75 int y=pos[p];
76 for (unsigned int i=0;i<querys[y].size();i++) ans[querys[y][i].second]=G.query(num[querys[y][i].first]);
77
78 }
79 else if (s[i]==‘B‘) G.change(p,-1),p=fa[p];
80 else p=son[p][s[i]-‘a‘],G.change(p,1);
81 }
82 }T;
83 int main(){
84 scanf("%s",s+1),len=strlen(s+1);
85 read(q);
86 for (int i=1;i<=q;i++) read(x),read(y),querys[y].push_back(make_pair(x,i));
87 T.init(),T.solve();
88 for (int i=1;i<=q;i++) printf("%d\n",ans[i]);
89 return 0;
90 }