#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <math.h>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <cassert>
#include <string.h>

#include <time.h>
#include <random>
#include <iomanip>
using namespace std;

#define ll long long
#define N 100000

map<char, pair<int, int> > m;


void solve() {
    string s;
    ll n;
    cin >> s >> n;
    
    vector<pair<int, string> > v(n, {0, ""});
    for (ll i = 0; i < n; i++) {
        cin >> v[i].second;
        
        for (ll j = 0; j < v[i].second.size(); j++) {
            v[i].first += abs(m[v[i].second[j]].first - m[s[j]].first);
            v[i].first += abs(m[v[i].second[j]].second - m[s[j]].second);
        }
    }
    sort(v.begin(), v.end());
    for (ll i = 0; i < v.size(); i++) {
        cout << v[i].second << " " << v[i].first << endl;
    }
}

int main() {
    string keyboard[3] = {"qwertyuiop","asdfghjkl","zxcvbnm"};
    for (ll i = 0; i < 3; i++) {
        for (ll j = 0; j < keyboard[i].size(); j++) {
            m[keyboard[i][j]] = {i,j};
        }
    }
    
    std::ios::sync_with_stdio(false);
    cin.tie(0);
    ll t;
    cin >> t;
    for (ll i = 0; i < t; i++) {
        solve();
    }
}