#include <cstdio>#include <iostream>#include <cctype>#include <cstring>#include <cstdlib>#include <algorithm>usingnamespacestd;
constint N = 1e5 + 5;
int G[N][26], pos[N], idx[N], fa[N], h[N];
int dfn[N], low[N], fail[N], c[N], ans[N]; char s[N];
int n, m, tis, T = 1;
inlineint get()
{
char ch; int res = 0; bool flag = false;
while (ch = getchar(), !isdigit(ch) && ch != '-');
(ch == '-' ? flag = true : res = ch ^ 48);
while (ch = getchar(), isdigit(ch))
res = res * 10 + ch - 48;
return flag ? -res : res;
}
struct Question
{
int x, y, t, s;
inlinebooloperator < (const Question &a) const
{
return y < a.y;
}
}q[N], g[N];
struct Edge
{
int to; Edge *nxt;
}p[N], *lst[N], *P = p;
inlinevoid Link(int x, int y)
{
(++P)->nxt = lst[x]; lst[x] = P; P->to = y;
}
inlinevoid Bfs()
{
for (int i = 0; i < 26; ++i) G[0][i] = 1;
h[1] = 1; int t = 0, w = 1, x, y;
while (t < w)
{
x = h[++t];
for (int i = 0; i < 26; ++i)
if (G[x][i])
{
h[++w] = G[x][i];
y = fail[x];
while (y > 0 && !G[y][i]) y = fail[y];
fail[G[x][i]] = G[y][i];
}
}
}
inlinevoid Dfs1(int x)
{
dfn[x] = ++tis;
for (Edge *e = lst[x]; e; e = e->nxt)
Dfs1(e->to);
low[x] = tis;
}
inlinevoid Modify(int x, int y)
{
for (; x <= tis; x += x & -x)
c[x] += y;
}
inlineint Query(int x)
{
int res = 0;
for (; x; x -= x & -x)
res += c[x];
return res;
}
inlinevoid Dfs2(int x)
{
Modify(dfn[x], 1);
if (idx[x])
for (int i = g[idx[x]].x, im = g[idx[x]].y; i <= im; ++i)
q[i].s = Query(low[pos[q[i].x]]) - Query(dfn[pos[q[i].x]] - 1);
for (int i = 0; i < 26; ++i)
if (G[x][i]) Dfs2(G[x][i]);
Modify(dfn[x], -1);
}
int main()
{
scanf("%s", s + 1); int x = 1;
for (int i = 1, im = strlen(s + 1); i <= im; ++i)
if (s[i] == 'B')
x = fa[x];
elseif (s[i] == 'P')
pos[++n] = x, idx[x] = n;
else
{
int y = s[i] - 'a';
if (!G[x][y]) fa[G[x][y] = ++T] = x;
x = G[x][y];
}
Bfs();
for (int i = 1; i <= T; ++i) Link(fail[i], i);
Dfs1(0);
m = get();
for (int i = 1; i <= m; ++i)
q[i].x = get(), q[i].y = get(), q[i].t = i;
sort(q + 1, q + m + 1);
int l = 1, r;
while (l < m)
{
r = l;
while (r < m && q[l].y == q[r + 1].y) ++r;
g[q[l].y].x = l; g[q[l].y].y = r;
l = r + 1;
}
Dfs2(1);
for (int i = 1; i <= m; ++i)
ans[q[i].t] = q[i].s;
for (int i = 1; i <= m; ++i) printf("%d\n", ans[i]);
return0;
}