#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=1e5+5;
inline int read(){
char c=getchar();int x=0,f=1;
while(c<‘0‘||c>‘9‘){if(c==‘-‘)f=-1; c=getchar();}
while(c>=‘0‘&&c<=‘9‘){x=x*10+c-‘0‘; c=getchar();}
return x*f;
}
int n,m;
char s[N];
struct ques{
int x,y,i;
bool operator <(const ques &r)const {return y<r.y;}
}a[N];
struct edge{
int v,ne;
}e[N<<1];
int cnt=0,h[N];
inline void ins(int u,int v){//printf("ins %d %d\n",u,v);
cnt++;
e[cnt].v=v;e[cnt].ne=h[u];h[u]=cnt;
cnt++;
e[cnt].v=u;e[cnt].ne=h[v];h[v]=cnt;
}
int din[N],dout[N],dfc;
void dfs(int u,int fa){
din[u]=++dfc;
for(int i=h[u];i;i=e[i].ne) if(e[i].v!=fa) dfs(e[i].v,u);
dout[u]=dfc;//printf("dfs %d %d %d\n",u,din[u],dout[u]);
}
struct node{
int ch[26],fa,fail;
}t[N];
int sz,pos[N],tot;
void build(char s[]){
int u=0;
for(int i=1;i<=n;i++){
if(s[i]==‘B‘) u=t[u].fa;
else if(s[i]==‘P‘) pos[++tot]=u;
else{
int c=s[i]-‘a‘;
if(!t[u].ch[c]) t[u].ch[c]=++sz;
t[t[u].ch[c]].fa=u;
u=t[u].ch[c];
}
}
//for(int i=0;i<=sz;i++) printf("build %d %d %d\n",i,t[i].fa,t[i].ch[0]);
}
int q[N],head,tail;
void getFail(){
head=tail=1;
for(int i=0;i<26;i++) if(t[0].ch[i])
q[tail++]=t[0].ch[i],ins(0,t[0].ch[i]);//!!!ins
while(head!=tail){
int u=q[head++];
for(int i=0;i<26;i++){
int &v=t[u].ch[i];
if(!v) {v=t[t[u].fail].ch[i];continue;}
t[v].fail=t[t[u].fail].ch[i];
q[tail++]=v;
ins(t[v].fail,v);
}
}
}
int c[N];
inline int lowbit(int x){return x&-x;}
inline void add(int p,int v){for(int i=p;i<=dfc;i+=lowbit(i))c[i]+=v;}//,printf("[add %d\n",i);}
inline int sum(int p){
int re=0;
for(int i=p;i;i-=lowbit(i)) re+=c[i];//,printf("sum %d %d\n",i,c[i]);
return re;
}
int ans[N];
void solve(){
sort(a+1,a+1+m);
build(s);
getFail();
dfs(0,-1);
int u=0,p=1,num=0;
for(int i=1;i<=n;i++){//printf("hi %d %c\n",i,s[i]);
if(s[i]==‘B‘) add(din[u],-1),u=t[u].fa;
else if(s[i]==‘P‘){
num++;
while(num==a[p].y){
int l=din[pos[a[p].x]],r=dout[pos[a[p].x]];
int t1=sum(l-1),t2=sum(r);//printf("que %d %d %d %d %d\n",a[p].i,l,r,t1,t2);
ans[a[p].i]=t2-t1;
p++;
}
}else{
int c=s[i]-‘a‘;
u=t[u].ch[c]; //printf("hehe %d %d\n",u,din[u]);
add(din[u],1);
}
//printf("u %d\n",u);
}
for(int i=1;i<=m;i++) printf("%d\n",ans[i]);
}
int main(){
//freopen("in.txt","r",stdin);
scanf("%s",s+1);m=read();
n=strlen(s+1);
for(int i=1;i<=m;i++) a[i].x=read(),a[i].y=read(),a[i].i=i;
solve();
}