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


using namespace std;

// problem I http://www.cs.ubc.ca/~acm-web/practice/2016-09-10/problems/problemset_2012.pdf

class SuperString {
public:
	string val;
	int coeficient;
	SuperString(string val);


};

SuperString::SuperString(string val) {
	SuperString::val = val;
}

bool fncomp(SuperString lhs, SuperString rhs) { 
	if (lhs.coeficient == rhs.coeficient) {
		return lhs.val < rhs.val;
	}
	return lhs.coeficient < rhs.coeficient; }

map<char, pair<int, int>> board;




// TODO: implement 
int calculateCoeficient(SuperString ss, string s) {
	int counter = 0;
	for (int i = 0; i < s.length(); i++)
	{
		counter += abs( std::get<0>(board[s[i]]) - std::get<0>(board[ss.val[i]]) );

		counter += abs( std::get<1>(board[s[i]]) - std::get<1>(board[ss.val[i]]) );

	}
	return counter;
}



int main()
{

	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;
	bool(*fn_pt)(SuperString, SuperString) = fncomp;
	std::set<SuperString, bool(*)(SuperString, SuperString)> list(fn_pt); // a set with my custom string objects, with custom comparator

	for (int i = 0; i < t; i++) {
		string s;
		int l;
		cin >> s;
		cin >> l;
		string input;

		for (int j = 0; j < l; j++) {
			// read word 
			cin >> input;

			// create SuperString
			SuperString ss = SuperString(input);


			// calculate coeficient
			ss.coeficient = calculateCoeficient(ss, s);

			// insert in set
			list.insert(ss);
		}

		// print all strings
		for (auto f : list) {
			cout << f.val << " " << f.coeficient << endl;
		}

		list.clear();
	}



	return 0;
}