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

char keys[][10] = {{'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'},
        {'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ' '},
        {'z', 'x', 'c', 'v', 'b', 'n', 'm', ' ', ' ', ' '}};

map<char, pair<int, int>> keyCoords;
map<int, set<string>> results;

int calcDistance(string a, string b) {
        int sum = 0;
        for (int i = 0; i < a.length(); i++) {
                sum += abs(keyCoords[a[i]].first - keyCoords[b[i]].first) +
                        abs(keyCoords[a[i]].second - keyCoords[b[i]].second);
        }
        return sum;
}

int main() {
        ios::sync_with_stdio(0);
        cin.tie(0);

        for (int j = 0; j < 3; j++) {
                for (int i = 0; i < 10; i++) {
                        keyCoords[keys[j][i]] = make_pair(j, i);
                }
        }

        int t;
        cin >> t;

        while (t--) {
                string s;
                string t;
                int l;
                cin >> s >> l;
                results.clear();
                for (int i = 0; i < l; i++) {
                        cin >> t;
                        int distance = calcDistance(s, t);
                        results[distance].insert(t);
                }

                for (auto p : results) {
                        for (auto s : p.second) {
                                cout << s << ' ' << p.first << endl;
                        }
                }
        }
        return 0;
}