Click Here to go back to the homepage.

Touchscreen Keyboard Solution:


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

char keyboard[3][10]= {{'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'}, 
                    {'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ' '},
                    {'z', 'x', 'c', 'v', 'b', 'n', 'm', ' ', ' ', ' '}};

pair<int, int> find(char c){
    for(int i = 0; i < 3; i++)
        for(int j = 0; j < 10; j++)
            if(keyboard[i][j] == c)
                return {i, j};
    return {-1, -1};
}

int dist(string word, string word2){
    int dist = 0;
    for(int i = 0; i < word.size(); i++){
        pair<int, int> xLoc = find(word.at(i));
        pair<int, int> yLoc = find(word2.at(i));
        dist += abs(xLoc.first - yLoc.first) + abs(xLoc.second - yLoc.second);
    }
    return dist;
}

int main(){
    // #ifndef TESTING
    // freopen("input.txt", "r", stdin);
    // freopen("output.txt", "w", stdout);
    // #endif

    int cases, suggestions;
    cin >> cases;
    string word, suggestion;
    while(cases--){
        cin >> word >> suggestions;
        vector<pair<string, int>> v(suggestions);
        while(suggestions--){
            cin >> suggestion;
            v[suggestions] = {suggestion, dist(word, suggestion)};
        }
        sort(v.begin(), v.end(), [](pair<string, int> p1, pair<string, int> p2){
            return p1.second == p2.second ? p1.first < p2.first : p1.second < p2.second;
        });
        for(auto i: v) cout << i.first << " " << i.second << endl;
    }

    return 0;
}