#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
int read()
{
int x=0;char ch=getchar();
while(ch<‘0‘||ch>‘9‘)ch=getchar();
while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘;ch=getchar();}
return x;
}
#define N 210000
int son[N][30],fail[N],q[N],sz,t,len,m,ans[N],fa[N],loc[N];
char s[N],opt[N];
struct data{int to,next;}edge[N],ask[N];
int cn,cnt,head[N],heada[N],lastq[N];
void addedge(int u,int v)
{cnt++;edge[cnt].to=v;edge[cnt].next=head[u];head[u]=cnt;}
void addask(int x,int y,int z)
{ask[z].next=heada[y];heada[y]=z;ask[z].to=x;}
int tree[N];
inline int lowbit(int x){return x&(-x);}
void change(int loc,int val)
{
for (int i=loc; i<=t; i+=lowbit(i))
tree[i]+=val;
}
int query(int loc)
{
int ans=0;
for (int i=loc; i>=1; i-=lowbit(i))
ans+=tree[i];
return ans;
}
int L[N],R[N];
void dfs(int x)
{
L[x]=++t;
for (int i=head[x]; i; i=edge[i].next)
dfs(edge[i].to);
R[x]=++t;
//printf("L=%d R=%d\n",L[x],R[x]);
}
void clear()
{sz=1;for (int i=0; i<26; i++) son[0][i]=1;}
void buildTrie()
{
int x=1,id=0;
for (int i=0; i<len; i++)
if (opt[i]==‘P‘) loc[++id]=x;
else if (opt[i]==‘B‘) x=fa[x];
else
{
if (!son[x][opt[i]-‘a‘])
son[x][opt[i]-‘a‘]=++sz,fa[sz]=x;
x=son[x][opt[i]-‘a‘];
}
}
void buildFail()
{
int he=0,ta=1; q[0]=1; fail[1]=0;
while (he<ta)
{
int now=q[he++];
for (int i=0; i<26; i++)
{
if (!son[now][i]) continue;
int ff=fail[now];
while (!son[ff][i]) ff=fail[ff];
fail[son[now][i]]=son[ff][i];
q[ta++]=son[now][i];
}
}
for (int i=1; i<=sz; i++)
addedge(fail[i],i);
}
void work()
{
int now=1,id=0;
change(L[1],1);
for (int i=0; i<len; i++)
if (opt[i]==‘P‘)
{
id++;
for (int j=heada[id]; j; j=ask[j].next)
ans[j]=query(R[loc[ask[j].to]])-query(L[loc[ask[j].to]]-1);
}
else if (opt[i]==‘B‘) change(L[now],-1),now=fa[now];
else now=son[now][opt[i]-‘a‘],change(L[now],1);
}
//ACMachine
int main()
{
clear();
scanf("%s",opt); len=strlen(opt);
buildTrie(); buildFail();
m=read();
for (int x,y,i=1; i<=m; i++)
x=read(),y=read(),addask(x,y,i);
dfs(0); work();
for (int i=1; i<=m; i++)
printf("%d\n",ans[i]);
return 0;
}