题目描述
You are given n words of equal length m, consisting of lowercase Latin alphabet letters. The i-th word is denoted si.
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 (1≤t≤100) — the number of test cases. The description of test cases follows.
The first line of each test case contains 2 integers n and m (2≤n≤50, 1≤m≤8) — 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.
输入样例
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
输出样例
11
8
35
0
200
4
样例解释
For the second test case, one can show that the best pair is (“abb”,”bef”), which has difference equal to 8, which can be obtained in the following way: change the first character of the first string to ‘b’ in one move, change the second character of the second string to ‘b’ in 3 moves and change the third character of the second string to ‘b’ in 4 moves, thus making in total 1+3+4=8 moves.
For the third test case, there is only one possible pair and it can be shown that the minimum amount of moves necessary to make the strings equal is 35.
For the fourth test case, there is a pair of strings which is already equal, so the answer is 0.
题目翻译:
给定一定数目的单词,对于每个单词中,其单个字母可以拉丁字母的顺序移动,以满足和参照单词相同,求出这一组单词当中,移动距离最小的那组单词的移动组数
1.单个字符之间可以用ascii值来相减转换成数值,因此不用map存取数字(如果闲的没事也可以先用map给26个英文字母进行一波赋值)
2.用指针去枚举,i枚举当前被比较行,j枚举比较行,k枚举列,去出每一组之间的差值绝对值的和
3.最小值处理:
每一组中取最小值
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 100;
string str[N];
int t;
//map<string,int>mp;
int main()
{
cin>>t;
/* mp['a']=1,mp['b']=2,mp['c']=3,mp['d']=4,mp['e']=5,mp['f']=6,mp['g']=7,mp['h']=8,mp['i']=9,mp['j']=10,mp['k']=11,mp['l']=12,
mp['m']=13,mp['n']=14,mp['o']=15,mp['p']=16,mp['q']=17,mp[r]=18,*/
while(t--)
{
int n,m;
int res=2e9;//总共的移动步数,取最小值
cin>>n>>m;
//将n组字符串进行读入并且统一处理
for(int i=0;i<n;i++)
{
cin>>str[i];
}
for(int i=0;i<n;i++){
//对于i组串进行依次的比较 i枚举的是被比较行,j是比较行,k是比较列
for(int j=0;j<i;j++)
{
int cnt=0;//每一组之间的移动更新数
for(int k=0;k<m;k++)
{
cnt+=abs(str[i][k]-str[j][k]);
}
res=min(res,cnt);//算完该组后更新
}
}
cout<<res<<endl;
}
return 0;
}