#include <iostream>
#include <string>
#include <cmath>
#include <utility>
#include <map>
#include <set>

using namespace std;

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

string s1 = "qwertyuiop";
string s2 = "asdfghjkl";
string s3 = "zxcvbnm";

map <char, pii> m;
int getDist(char a, char b);
int main() {
	m['q'] = pii(0, 0);
	m['w'] = pii(1, 0);
	m['e'] = pii(2, 0);
	m['r'] = pii(3, 0);
	m['t'] = pii(4, 0);
	m['y'] = pii(5, 0);
	m['u'] = pii(6, 0);
	m['i'] = pii(7, 0);
	m['o'] = pii(8, 0);
	m['p'] = pii(9, 0);
	m['a'] = pii(0, 1);
	m['s'] = pii(1, 1);
	m['d'] = pii(2, 1);
	m['f'] = pii(3, 1);
	m['g'] = pii(4, 1);
	m['h'] = pii(5, 1);
	m['j'] = pii(6, 1);
	m['k'] = pii(7, 1);
	m['l'] = pii(8, 1);
	m['z'] = pii(0, 2);
	m['x'] = pii(1, 2);
	m['c'] = pii(2, 2);
	m['v'] = pii(3, 2);
	m['b'] = pii(4, 2);
	m['n'] = pii(5, 2);
	m['m'] = pii(6, 2);

	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 += getDist(temp[i], s[i]);
			}
			ss.insert(pis(count, temp));
		}
		for (pis is : ss) {
			cout << is.second << " " << is.first << endl;
		}
	}
	return 0;
}

int getDist(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);
}