#include<map>
#include<deque>
#include<stack>
#include<queue>
#include<cmath>
#include<vector>
#include<climits>
#include<iostream>
#include<algorithm>
#include<unordered_map>
#define il inline
#define ll long long
const ll mod=1e9+7;
const ll inf=0x3f3f3f3f;
const double pi=acos(-1.0);
const double Exp=1e-8;
il int read(){
int x=0,t=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')t=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
return x*t;
}
il void write(int x){
if(x<0){putchar('-');x=-x;}
if(x>9)write(x/10);
putchar(x%10+'0');
}
struct Node{
std::string curStr;
int step;
};
std::string raw;
int main(){
std::cin>>raw;
int m=read();
while(m--){
std::map<std::string,bool>vis;
std::string s;std::cin>>s;
std::queue<Node>q;
q.push({raw,0});
while(q.size()){
Node cur=q.front();
q.pop();
if(cur.curStr==s){
std::cout<<cur.step<<std::endl;
goto Night;
}
for(int i=1;i<cur.curStr.size();i++){
Node next;
next.curStr=cur.curStr;
next.step=cur.step;
std::swap(next.curStr[i],next.curStr[i-1]);
if(!vis[next.curStr]){
vis[next.curStr]=1;
next.step++;
q.push(next);
}
}
if(cur.curStr.size()==raw.size()){
for(int i=0;i<cur.curStr.size();i++){
Node next;
next.curStr=cur.curStr;
next.step=cur.step;
next.curStr.erase(i,1);
if(!vis[next.curStr]){
vis[next.curStr]=1;
next.step++;
q.push(next);
}
}
}
if(cur.curStr.size()<raw.size()){
for(int i=0;i<cur.curStr.size()-1;i++){
for(int j=cur.curStr[i]-48+1;j<cur.curStr[i+1]-48;j++){
Node next;
next.curStr=cur.curStr;
next.step=cur.step;
next.curStr.insert(i+1,std::to_string(j));
if(!vis[next.curStr]){
vis[next.curStr]=1;
next.step++;
q.push(next);
}
}
}
}
}
puts("-1");
Night:;
}
}