#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int main() {
    string s; 
    cin >> s;
    vector <int> parts;
    
    ll l = 0, r1, r2;
    for (int i = 1; i < s.size(); i++) {
        if (int(s[i]) < int(s[i - 1])) {
            parts.push_back(l);
            l = i;
        }
    }
    parts.push_back(l);
    parts.push_back(s.size() + 1);
    
    ll t, r, n = parts.size();
    cin >> t;
    while (t--) {
        cin >> l >> r;
        r--;
 
        for (int i = 0; i < n - 1; i++) 
            if (parts[i] <= l && parts[i+1] > l) {
                r1 = i;
                break;
            }
         
        for (int i = n - 1; i >= 1; i--) 
            if (parts[i - 1] <= r && parts[i] > r) {
                r2 = i;
                break;
            }
        cout << r2 - r1 << endl;
    }
}

/*abc aabb acccc b
   bcaabbaccccb
    caabbac
   bcaabbacc
      abbaccccb
      abb*/