#include <iostream>
#include <algorithm>

using namespace std;
typedef pair<int, string> pis;

int dist[26][26];

void initmap() {
	string keys[3] = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};
	int x[26], y[26];
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < keys[i].length(); j++) {
			int c = (int)(keys[i][j] - 'a');
			x[c] = j;
			y[c] = i;
		}
	}
	for (int i = 0; i < 26; i++) {
		for (int j = 0; j < 26; j++) {
			dist[i][j] = abs(x[i] - x[j]) + abs(y[i] - y[j]);
		}
	}
}

pis arr[20];
int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	initmap();
	int ncase; cin >> ncase;
	while (ncase--) {
		string s; int n; cin >> s >> n;
		for (int i = 0; i < n; i++) {
			string s2; cin >> s2;
			int d = 0;
			for (int j = 0; j < s.length(); j++) {
				d += dist[s[j] - 'a'][s2[j] - 'a'];
			}
			arr[i] = pis(d, s2);
		}
		sort(arr, arr+n);
		for (int i = 0; i < n; i++) {
			cout << arr[i].second << " " << arr[i].first << endl;
		}
	}
}