Under construction

Still being built. Things may change

Touchscreen Keyboard

Interview

Time limit1sMemory limit128 MB

Summary
Given a typed word and a list of same-length dictionary words, print each with its keyboard Manhattan distance, sorted by distance then lexicographically.
Level

Medium4 of 10

Topics
String, Sorting, Implementation, Hash map
Solved
No attempts yet

Problem

These days many people type on touchscreen keyboards. Because the keys sit close together and each key is small, typos happen very often.

To reduce these typos, a spell-check program was written. Despite its name, it only checks for typos.

When the user enters a word, the program takes from its own list the correct words that have the same length as the input and recommends them in order of similarity, showing the most similar word first.

The touchscreen keyboard is laid out like this:

qwertyuiop
asdfghjkl
zxcvbnm

The similarity of two words is measured by their distance on the keyboard. The distance between two words is the sum, over each matching position, of the distance between the two characters there. The distance between two characters is the number of columns apart plus the number of rows apart on the keyboard.

For example, taking w as the reference, its distance to e is 1 and its distance to z is 3. Likewise, the distance between the words icpc and ifpv is 3. The smaller the distance, the more similar the words are.

Input

The first line contains the number of test cases tt (0<t<20)(0 < t < 20).

The first line of each test case contains the word entered by the user and ll (0<l≤10)(0 < l \le 10), the number of words the program knows. Each of the next ll lines contains one of the program's words. Every one of these words has the same length as the user's word, consists only of lowercase letters, and is at most 10,000 characters long. No word appears more than once.

Output

For each test case, sort the recommended words by increasing distance and print each word together with its distance, one per line. If several words have the same distance, order them lexicographically.

Examples3

  1. Example 1

    Input
    2
    ifpv 3
    iopc
    icpc
    gcpc
    edc 5
    wsx
    edc
    rfv
    plm
    qed
    
    Expected output
    icpc 3
    gcpc 7
    iopc 7
    edc 0
    rfv 3
    wsx 3
    qed 4
    plm 17
    
  2. Example 2

    Input
    1
    a 1
    a
    
    Expected output
    a 0
    
  3. Example 3

    Input
    1
    e 2
    w
    r
    
    Expected output
    r 1
    w 1