1 #include<cstdio>
2 #include<cstring>
3 #include<string>
4 #include<vector>
5 using namespace std;
6 const int L=100000;
7 int m,num,cnt,cnt_type,hd=1,tl;char text[L+100];
8 int e,adj[L+100],bit[L+100],ans[L+100];
9 inline int lowbit(int a){return a&-a;}
10 inline void add(int pos,int val)
11 {
12 while(pos<=cnt)
13 bit[pos]+=val,pos+=lowbit(pos);
14 }
15 inline int sum(int pos)
16 {
17 int ret=0;
18 while(pos)
19 ret+=bit[pos],pos-=lowbit(pos);
20 return ret;
21 }
22 struct node
23 {
24 node *f,*fa,*ch[26];
25 int id,dfn_l,dfn_r,mark;
26 node(int v,node *o)
27 {
28 memset(ch,0,sizeof(ch));
29 id=v,mark=0;fa=o,f=NULL;
30 }
31 }*root=new node(0,NULL),*q[L+100],*print[L+100];
32 struct edge{node *qi,*zhong;int next;}s[L+100];
33 inline void get_fail()
34 {
35 q[++tl]=root;
36 while(hd<=tl)
37 {
38 node *rt=q[hd++];
39 for(int i=0;i<26;i++)
40 {
41 if(rt->ch[i])
42 {
43 q[++tl]=rt->ch[i];
44 node *u=rt->f;
45 while(u&&!u->ch[i])u=u->f;
46 rt->ch[i]->f=(u)?u->ch[i]:root;
47 }
48 }
49 }
50 }
51 inline void add(node *qi,node *zhong)
52 {
53 s[++e].qi=qi;s[e].zhong=zhong;
54 s[e].next=adj[qi->id],adj[qi->id]=e;
55 }
56 inline void build_fail(node *rt)
57 {
58 for(int i=0;i<26;i++)
59 if(rt->ch[i]!=NULL)
60 add(rt->ch[i]->f,rt->ch[i]),build_fail(rt->ch[i]);
61 }
62 void dfs(node *rt)
63 {
64 rt->dfn_l=++cnt;
65 for(int i=adj[rt->id];i;i=s[i].next)
66 if(s[i].zhong!=NULL)
67 dfs(s[i].zhong);
68 rt->dfn_r=cnt;
69 }
70 struct Quest{int id;node *pos;};
71 vector<Quest>quest[L+100];
72 void work(node *rt)
73 {
74 add(rt->dfn_l,1);
75 for(int i=0;i<quest[rt->id].size();i++)
76 {
77 Quest t=quest[rt->id][i];
78 ans[t.id]=sum(t.pos->dfn_r)-sum(t.pos->dfn_l-1);
79 }
80 for(int i=0;i<26;i++)
81 if(rt->ch[i]!=NULL)
82 work(rt->ch[i]);
83 add(rt->dfn_l,-1);
84 }
85 int main()
86 {
87 scanf("%s",text);int sea=strlen(text);
88 node *now=root;
89 for(int i=0;i<sea;i++)
90 {
91 if(text[i]==‘P‘)
92 {
93 now->mark=++cnt_type;
94 print[cnt_type]=now;
95 }
96 else if(text[i]==‘B‘)
97 now=now->fa;
98 else
99 {
100 if(!now->ch[text[i]-‘a‘])
101 now->ch[text[i]-‘a‘]=new node(++num,now);
102 now=now->ch[text[i]-‘a‘];
103 }
104 }
105 get_fail();build_fail(root);dfs(root);
106 scanf("%d",&m);int x,y;
107 for(int i=1;i<=m;i++)
108 {
109 scanf("%d%d",&x,&y);
110 quest[print[y]->id].push_back((Quest){i,print[x]});
111 }
112 work(root);
113 for(int i=1;i<=m;i++)printf("%d\n",ans[i]);
114 }