#include <iostream>
#include <cmath>
#include <algorithm>
typedef struct
{
	std::string word;
	int dist;
} pair;

int getIndex(char letter)
{
	char alphabet[] = "qwertyuiopasdfghjklzxcvbnm";
	
	int index=0;
	for(int i = 0; i < 26; i++)
	{
		if(letter == alphabet[i])
		{
			index = i;
			break;
		}
	}
	
	if(index >= 19 && index < 26)
	{
		//std::cout << 1;
		return index - 19;
	}
	else if(index >=10 && index < 19)
	{
//		std::cout << 2;
		return index - 10;
	}
//		std::cout << 3;
	return index;
}

int getHeight(char letter)
{
	char alphabet[] = "qwertyuiopasdfghjklzxcvbnm";
	
	int index=0;
	for(int i = 0; i < 26; i++)
	{
		if(letter == alphabet[i])
		{
			index = i;
			break;
		}
	}
	
	if(index >= 19 && index < 26)
	{
		//std::cout << 1;
		return 2;
	}
	else if(index >=10 && index < 19)
	{
//		std::cout << 2;
		return 1;
	}
//		std::cout << 3;
	return 0;
}

int getDist(char letter1, char letter2)
{
	int index1 = getIndex(letter1);
	int index2 = getIndex(letter2);
	
	int height1 = getHeight(letter1);
	int height2 = getHeight(letter2);
	return std::abs(index1 - index2) + std::abs(height1 - height2);
}

bool comparePair(pair lhs, pair rhs)
{
	if(lhs.dist == rhs.dist)
	{
		return lhs.word < rhs.word;
	}
	return lhs.dist < rhs.dist;
}

int main()
{
	int n;
	//get initial data
	std::cin >> n;
	
	for(int i = 0; i < n; i++) //read in pairs
	{
		std::string mainWord;
		int altWordCount = 0;
		std::cin >> mainWord >> altWordCount;
		
		std::string altWordArray[altWordCount];
		int altWordDist[altWordCount];
		for(int j = 0; j < altWordCount; j++) //read in pairs
		{
			std::cin >> altWordArray[j];
			altWordDist[j] = 0;
			for (int k = 0; k < (int)mainWord.length(); k++)
			{
				altWordDist[j] += getDist(mainWord[k], altWordArray[j][k]);
			}
		}
		
		pair altWordPairArray[altWordCount];
		
		for(int j = 0; j < altWordCount; j++) //read in pairs
		{
			altWordPairArray[j].word = altWordArray[j];
			altWordPairArray[j].dist = altWordDist[j];
		}
		
		std::sort(altWordPairArray, altWordPairArray+altWordCount, comparePair);
		
		for(int j = 0; j < altWordCount; j++) //read in pairs
		{
			std::cout << altWordPairArray[j].word << " " << altWordPairArray[j].dist << std::endl;
		}
	}

}