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

string G[3];
int dist[26][26];
vector<pii> delta={{0,1},{0,-1},{-1,0},{1,0}};
bool inGrid(int i, int j){
    if (i<0) return false; if (i>=3) return false;
    if (j<0) return false;
    if (j>=G[i].size()) return false;
    return true;
}
int main(){
    ios::sync_with_stdio(0);
    G[0]="qwertyuiop",G[1]="asdfghjkl",G[2]="zxcvbnm";
    for (int i=0;i<3;i++) for (int j=0;j<10;j++) if (inGrid(i,j)){
        int start=G[i][j]-'a';
        memset(dist[start],-1,sizeof dist[start]);
        queue<pii> q; q.push({i,j}); dist[start][start]=0;
        while (!q.empty()){
            pii now=q.front(); q.pop();
            for (pii dd:delta){
                pii nex={dd.first+now.first,dd.second+now.second};
                if ((inGrid(nex.first,nex.second))&&(dist[start][G[nex.first][nex.second]-'a']==-1)){
                    dist[start][G[nex.first][nex.second]-'a']=dist[start][G[now.first][now.second]-'a']+1;
                    q.push(nex);
                }
            }
        }
    }
    int t; cin>>t;
    while (t--){
        string s; int n; cin>>s>>n;
        set<pair<int,string>> ans;
        while (n--){
            string k; cin>>k;
            int val=0;
            for (int i=0;i<s.size();i++) val+=dist[s[i]-'a'][k[i]-'a'];
            ans.insert({val,k});
        }
        for (pair<int,string> p:ans) cout<<p.second<<' '<<p.first<<endl;
    }
    return 0;
}