#include<bits/stdc++.h>
using namespace std;
#define MAXN 10000010
#define long long ll
int t,q,l,r;
short a[MAXN] = {0};
string s;
int main() {
ios::sync_with_stdio(false);cin.tie(0);
cin >> t;
while(t--){
cin >> s >> q;
for(int i = 0;i < s.size();i++){
if(s[i] == 'P') a[i + 1] = a[i] + 3;
else if(s[i] == 'p') a[i + 1] = a[i] + 2;
else if(s[i] == 'G') a[i + 1] = a[i] + 1;
else a[i + 1] = a[i];
}
while(q--){
cin >> l >> r;
cout << a[r] - a[l - 1] << endl;
}
}
return 0;
}