CodeforcesSep 04, 2025

Most Similar Words

Hazrat Ali

Codeforces

In one move you can choose any position in any single word and change the letter at that position to the previous or next letter in alphabetical order. For example:

  • you can change 'e' to 'd' or to 'f';
  • 'a' can only be changed to 'b';
  • 'z' can only be changed to 'y'.

The difference between two words is the minimum number of moves required to make them equal. For example, the difference between "best" and "cost" is 1+10+0+0=11.

Find the minimum difference of si and sj such that (i<j). In other words, find the minimum difference over all possible pairs of the n words.

Input

The first line of the input contains a single integer t (1t100) — the number of test cases. The description of test cases follows.

The first line of each test case contains 2 integers n and m (2n501m8) — the number of strings and their length respectively.

Then follows n lines, the i-th of which containing a single string si of length m, consisting of lowercase Latin letters.

Output

For each test case, print a single integer — the minimum difference over all possible pairs of the given strings.

Example
Input
6
2 4
best
cost
6 3
abb
zba
bef
cdu
ooo
zzz
2 7
aaabbbc
bbaezfe
3 2
ab
ab
ab
2 8
aaaaaaaa
zzzzzzzz
3 1
a
u
y

Output
11
8
35
0
200
4

Solution

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

long long cost(string s, string t)
{
    long long c = 0;
    for (int i = 0; i < s.size(); i++)
    {
        c += abs(s[i] - t[i]);
    }
    return c;
}

int main()
{

    int t;
    cin >> t;
    while (t--)
    {
        int n, m;
        cin >> n >> m;
        vector<string> s(n);
        for (int i = 0; i < n; i++)
        {
            cin >> s[i];
        }
        long long ans = INT_MAX;
        for (int i = 0; i < n - 1; i++)
        {
            for (int j = i + 1; j < n; j++)
            {
                ans = min(ans, cost(s[i], s[j]));
            }
        }
        cout << ans << "\n";
    }
    return 0;
}



Comments