#include <bits/stdc++.h>
using namespace std;
#define int long long
vector<pair<int, int>> t;
vector<pair<int, int>> t1;
vector<int> pref;
vector<int> suf;
void build(int i, int l, int r){
if(l == r){
t[i].first = pref[l];
t[i].second = l;
return;
}
int mid = (l+r)/2;
build(i*2, l, mid);
build(i*2+1, mid+1, r);
if(t[i*2] < t[i*2+1]){
t[i] = t[i*2];
}else{
t[i] = t[i*2+1];
}
}
pair<int, int> ns = {1e18, 0};
void query(int i, int l, int r, int l1, int r1){
if(l1 > r || l > r1) return;
if(l <= l1 && r >= r1){
if(ns.first >= t[i].first){
ns = t[i];
}
return;
}
int mid = (l+r)/2;
query(i*2, l, mid, l1, r1);
query(i*2+1, mid+1, r, l1, r1);
}
void build1(int i, int l, int r){
if(l == r){
t1[i].first = suf[l];
t1[i].second = l;
return;
}
int mid = (l+r)/2;
build1(i*2, l, mid);
build1(i*2+1, mid+1, r);
if(t1[i*2] <= t1[i*2+1]){
t1[i] = t1[i*2];
}else{
t1[i] = t1[i*2+1];
}
}
void query1(int i, int l, int r, int l1, int r1){
if(l1 > r || l > r1) return;
if(l <= l1 && r >= r1){
if(ns.first > t1[i].first){
ns = t1[i];
}
return;
}
int mid = (l+r)/2;
query1(i*2, l, mid, l1, r1);
query1(i*2+1, mid+1, r, l1, r1);
}
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int n; cin >> n;
t.resize((n+1)*4);
t1.resize((n+1) * 4);
string x; cin >> x;
x = '?' + x;
pref.resize(n+1);
int co = 0;
vector<int> p(n+1);
int co1 = 0;
for(int i = 1; i <= n; i++){
if(x[i] == 'C'){
co++;
}else{
co1++;
co--;
}
p[i] = co1;
pref[i] = co;
}
suf.resize(n+2);
co = 0;
for(int i = n; i >= 1; i--){
if(x[i] == 'C'){
co++;
}else{
co--;
}
suf[i] = co;
}
build(1, 1, n);
build1(1, 1, n);
int q; cin >> q;
while(q--){
int l, r; cin >> l >> r;
ns = {1e18, 1e18};
query(1, 1, n, l, r);
pair<int, int> f = ns;
ns = {1e18, 1e18};
query1(1, 1, n, l, r);
//f and ns
int a = f.first - pref[l-1];
int b = ns.first - suf[r+1];
if(a >= 0 && b >= 0){
cout << 0 << "\n";
continue;
}else if(a >= 0){
cout << b << "\n";
continue;
}else if(ns.first >= 0){
cout << a << "\n";
continue;
}
a = abs(a);
b = abs(b);
if(f.second < ns.second){
cout << a+b << "\n";
continue;
}
int here = p[f.second] - p[ns.second-1];
if(a >= here && b >= here){
cout << a+b-here << "\n";
}else{
cout << max(a, b) << "\n";
}
}
return 0;
}