#include <bits/stdtr1c++.h>

using namespace std;

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

map<char, pii> board;

struct cmp {
  bool operator()(const psi &a, const psi &b) {
    if (a.second== b.second)
      return a.first< b.first;
    return a.second < b.second;
  }
};

int main() {
  ios_base::sync_with_stdio(0);
  board['q'] = {0,0};
  board['w'] = {0,1};
  board['e'] = {0,2};
  board['r'] = {0,3};
  board['t'] = {0,4};
  board['y'] = {0,5};
  board['u'] = {0,6};
  board['i'] = {0,7};
  board['o'] = {0,8};
  board['p'] = {0,9};
  board['a'] = {1,0};
  board['s'] = {1,1};
  board['d'] = {1,2};
  board['f'] = {1,3};
  board['g'] = {1,4};
  board['h'] = {1,5};
  board['j'] = {1,6};
  board['k'] = {1,7};
  board['l'] = {1,8};
  board['z'] = {2,0};
  board['x'] = {2,1};
  board['c'] = {2,2};
  board['v'] = {2,3};
  board['b'] = {2,4};
  board['n'] = {2,5};
  board['m'] = {2,6};
  int t; cin >> t;
  while (t--) {
    string wrd; cin >> wrd;
    int num; cin >> num; 
    vector<string> v(num);
    set<pair<string, int>, cmp> res;
    for (int i=0; i<num; i++) {
      string s; cin >> s;
      int tmp = 0;
      for (int j=0; j<s.size(); j++) {
tmp += (abs(board[s[j]].first - board[wrd[j]].first));
        tmp += (abs(board[s[j]].second - board[wrd[j]].second));
      }
      res.insert({s,tmp});
    }
    for (auto x : res) {
      cout << x.first << " " << x.second << endl;
    }
  }
}