#include <bits/stdc++.h>
using namespace std;
int a[100010],s1[100010];
int main(){
int t;
cin>>t;
while(t--){
string s;
cin>>s;
for(int i=1;i<=s.size();i++){
if(s[i]=='P')a[i]=3;
if(s[i]=='p')a[i]=2;
if(s[i]=='G')a[i]=1;
if(s[i]=='g')a[i]=0;
if(s[i]=='m')a[i]=0;
s[i]=s[i-1]+a[i];
}
int q;
cin>>q;
while(q--){
int l;
int r;
cin>>l>>r;
cout<<s[r]-s[l-1];
}
}
return 0;
}