#include<bits/stdc++.h>
using namespace std;
int a[100005], he[100005];
void dx(string k)
{
int z = 0;
for(int i = 0; i < k.size(); i ++)
{
if(k[i] == 'P')
{
a[i] += 3;
}
else if(k[i] == 'p')
{
a[i] += 2;
}
else if(k[i] == 'G')
{
a[i] += 1;
}
}
}
int main()
{
int t;
cin >> t;
for(int i = 1; i <= t; i ++)
{
string s;
cin >> s;
dx(s);
int q;
cin >> q;
he[0] = 0;
for(int j = 1; j <= q; j ++)
{
he[j] = he[j - 1] + a[j];
}
for(int j = 1; j <= q; j ++)
{
int l, r;
cin >> l >> r;
cout << he[r] - he[l - 1] << endl;
}
}
return 0;
}