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

unsigned T, L;
string word;

int X[26], Y[26];
string keyrow[] = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};

int dist(char a, char b){
	return abs(X[b-'a'] - X[a-'a']) + abs(Y[b-'a'] - Y[a-'a']);
}

struct WordDist{
	int d;
	string w;
};

vector<WordDist> v;

bool cmp (WordDist a, WordDist b){ 
	if (a.d == b.d){
		return a.w < b.w;
	}
	else{
		return (a.d < b.d); 
	}
} 

int main(void){

	unsigned row,col;
	for (row=0; row<3; ++row){
		for (col=0; col<keyrow[row].length(); ++col){
			X[keyrow[row][col] - 'a'] = row;
			Y[keyrow[row][col] - 'a'] = col;
		}
	}

	cin >> T;

	unsigned tc;
	for (tc = 0; tc < T; ++tc){
		v.clear();
		cin >> word >> L;
		unsigned i, j;

		WordDist wd;
		for (i=0; i<L; ++i){
			cin >> wd.w;
			wd.d = 0;
			for (j=0; j<word.length(); ++j){
				wd.d +=  dist(word[j], wd.w[j]);
			}
			v.push_back(wd);
		}

		sort(v.begin(), v.end(), cmp);

		for (i=0; i<L; ++i){
			cout << v[i].w << " " << v[i].d << '\n';
		}
	}

	return 0;
}