#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const int M = 1e4+7;
const int N = 2e3+10;
const int base = 13331;
struct HASHMAP { //构造map,直接用map会tle(套用kuangbin大佬模板);
int head[M],next[N],size;
ull state[N];
int f[N];
void init(){
size = 0;
memset(head,-1,sizeof head);
}
int insert(ull val,int _id) {
int h = val%M;
for(int i = head[h]; i != -1; i = next[i])
if(val == state[i]){
int tmp = f[i];
f[i] = _id;
return tmp;
}
f[size] = _id;
state[size] = val;
next[size] = head[h];
head[h] = size++;
return 0;
}
} H;
const int P=131;
ull pre[N],a[N],dp[N][N];int n,t;string s;
int main(){
pre[0]=1;for(int i=1;i<N;i++) pre[i]=pre[i-1]*P;
while(scanf("%d",&n)!=EOF){
memset(dp,0,sizeof dp);
cin>>s;for(int i=0;i<s.size();i++) a[i+1]=a[i]*P+s[i]-'a';
int n=s.size();
for(int i=1;i<=n;i++){
H.init();
for(int j=1;j+i-1<=n;j++){
int l=H.insert(a[j+i-1]-a[j-1]*pre[i],j);
dp[j][j+i-1]++;
dp[l][j+i-1]--;
}
}
for(int i=n;i>=0;i--){
for(int j=i;j<=n;j++){
dp[i][j]+=dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1];
}
}
scanf("%d",&t);
while(t--){
int l,r;scanf("%d%d",&l,&r);
cout<<dp[l][r]<<endl;
}
}
}