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

typedef pair<int,int> pii;
typedef pair<int,string> pis;

string k[3] = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};
map<char,pii> m;

int main() {
  ios::sync_with_stdio(0);
  for (char c = 'a'; c <= 'z'; c++) {
    for (int i = 0; i < 3; i++) {
      for (int j = 0; j < k[i].size(); j++) {
        if (k[i][j] == c) {
          m[c] = make_pair(i,j);
          goto VELOCIRAPTOR;
        }
      }
    }
VELOCIRAPTOR:
    ;
  }
  int t; cin >> t;
  while (t--) {
    string s; int l;
    cin >> s >> l;
    vector<pis> v;
    while (l--) {
      string w; cin >> w;
      int d = 0;
      for (int i = 0; i < s.size(); i++)
        d += abs(m[s[i]].first-m[w[i]].first)+abs(m[s[i]].second-m[w[i]].second);
      v.push_back(make_pair(d,w));
    }
    sort(v.begin(),v.end());
    for (pis p : v)
      cout << p.second << " " << p.first << "\n";
  }
  return 0;
}