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

typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
typedef pair<int,string> pis;
typedef vector<int> vi;

#define endl '\n'

string s[] = {"qwertyuiop","asdfghjkl","zxcvbnm"};
string alph = "abcdefghijklmnopqrstuvwxyz";

map <char, pii> m;

int dist(char a, char b) {
    int count = 0;
    pii p1 = m[a];
    pii p2 = m[b];
    return abs(p1.first - p2.first) + abs(p1.second - p2.second);
}

int main() {
	ios::sync_with_stdio(0);
	for (int i=0; i<alph.length(); i++) {
		for(int j=0; j<=2; j++) {
			if (s[j].find(alph[i]) != string::npos) m[alph[i]] = pii(s[j].find(alph[i]),j);
		} 
	}

	int t;
    cin >> t;
    while (t--) {
        set<pis> ss;
        string s;
        cin >> s;
        int n;
        cin >> n;
        for (int i = 0; i < n; i++){
            string temp;
            cin >> temp;
            int count = 0;
            for (int i = 0; i < temp.length(); i++) {
                count += dist(temp[i], s[i]);
            }
            ss.insert(pis(count, temp));
        }
        for (pis is : ss) {
            cout << is.second << " " << is.first << endl;
        }
    }

	return 0;
}