// PROBLEM I
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

struct Outputs {
	int dist;
	char str[20000];
} outputs[20];

int clac_distance(char first, char second) {
	char *keyboard[] = {
		"qwertyuiop",
		"asdfghjkl",
		"zxcvbnm",
	};
	int i, j, pos_ax = -1, pos_bx = -1, pos_ay = -1, pos_by = -1;
	if(first == second) return 0;
	for (i = 0; i < 3; i += 1) {
		for (j = 0; j < strlen(keyboard[i]); j += 1) {
			if (first == keyboard[i][j]) {
				pos_ax = i;
				pos_ay = j;
			}
			if (second == keyboard[i][j]) {
				pos_bx = i;
				pos_by = j;
			}
			if (pos_ax != -1 && pos_bx != -1) break;
		}
	}
	return abs(pos_ax - pos_bx) + abs(pos_ay - pos_by);
}

int calc_str_dist(char *str_a, char *str_b) {
	int i = 0, total_dist = 0;
	if(strlen(str_a) != strlen(str_b)) {
		printf("length x same");
		return -1;
	}
	for (i = 0; i < strlen(str_a); i += 1) {
		total_dist += clac_distance(str_a[i], str_b[i]);
	}
	return total_dist;
}

int compare(const void *p1,const void *p2) {
	struct Outputs *c = (struct Outputs *)p1;
	struct Outputs *d = (struct Outputs *)p2;
	if(c->dist != d->dist)
		return c->dist - d->dist;
	return strcmp(c->str, d->str);
}

void print_result(int inputs) {
	int i = 0;
	qsort(outputs, inputs, sizeof(outputs[0]), compare);
	for(i = 0; i < inputs; i += 1) {
		printf("%s %d\n", outputs[i].str, outputs[i].dist);
		outputs[i].str[0] = '\0';
		outputs[i].dist = 0;
	}
	
}

int main(void) {
	int i = 0, times = 0;
	//printf("%d\n", clac_distance('w', 'z'));
	scanf("%d", &times);
	for(i = 0; i < times; i += 1) {
		int j = 0, inputs = 0;
		char std_input[20000];
		scanf("%s %d", std_input, &inputs);
		for(j = 0; j < inputs; j += 1) {
			scanf("%s", outputs[j].str);
			outputs[j].dist = calc_str_dist(std_input, outputs[j].str);
			//printf("%s %d\n", usr_input, total_dist);
		}
		print_result(inputs);
	}
	return 0;
}