#include <bits/stdc++.h>

using namespace std;

#define range(i,a,b) for(int i=(a);i<(b);++i)
#define rep(i,n)  range(i,0,n)

void suffix_array(string s,int *sa){
	int n=s.size();
	vector<int> rank(n+1,0),tmp(n+1,0);
	rep(i,n+1) sa[i]=i,rank[i]=(i<n?s[i]:-1);

	for(int k=1;k<=n;k<<=1){
		auto cmp=[&](int i,int j){
			if(rank[i]!=rank[j]) return rank[i]<rank[j];
			int ci=(i+k<=n)?rank[i+k]:-1;
			int cj=(j+k<=n)?rank[j+k]:-1;
			return ci<cj;
		};
		sort(sa,sa+n+1,cmp);
		tmp[sa[0]]=0;
		rep(i,n) tmp[sa[i+1]]=tmp[sa[i]]+cmp(sa[i],sa[i+1]);
		rep(i,n+1) rank[i]=tmp[i];
	}
	return;
}

const int nmax=250010;
int sa[nmax],len[nmax];
string s;

int sprase_table[2][nmax][20];

void init(int *a,int n){
	int logn=31-__builtin_clz(n);
	rep(i,n) sprase_table[0][i][0]=sprase_table[1][i][0]=a[i];
	rep(k,logn)rep(i,n+1-(1<<k)){
		sprase_table[0][i][k+1]=min(sprase_table[0][i][k],sprase_table[0][i+(1<<k)][k]);
		sprase_table[1][i][k+1]=max(sprase_table[1][i][k],sprase_table[1][i+(1<<k)][k]);
	}
	return ;
}

int query(int l,int r,int type){
	int i=31-__builtin_clz(r-l);
	if(type==0)
		return min(sprase_table[0][l][i],sprase_table[0][r-(1<<i)][i]);
	else
		return max(sprase_table[1][l][i],sprase_table[1][r-(1<<i)][i]);
}

int b_search(string x,int type,int n){
	int from,to,l,r;

	l=0,r=n;
	while(r-l>1){
		int m=(l+r)/2;
		if(s.substr(sa[m],x.size())<x)
			l=m;
		else
			r=m;
	}

	if(s.substr(sa[r],x.size())!=x) return -1;
	from=r;

	l=1,r=n+1;
	while(r-l>1){
		int m=(l+r)/2;
		if(s.substr(sa[m],x.size())<=x)
			l=m;
		else
			r=m;
	}
	if(s.substr(sa[l],x.size())!=x) return -1;
	to=l;
	if(from>to) return -1;
	return query(from,to+1,type);
}

int main(void){
	cin >> s;
	int n=s.size();
	suffix_array(s,sa);
	rep(i,n+1) len[i]=s.substr(sa[i]).size();
	init(len,n+1);

	int m;
	cin >> m;
	rep(loop,m){
		string x,y;
		cin >> x >> y;
		int from=b_search(x,1,n),to=b_search(y,0,n);
		int ans=0;
		if(from!=-1&&to!=-1&&(from-x.size())>=to-y.size()) ans=from-to+y.size();
		cout << ans << endl;
	}
	return 0;
}