You are given nn words of equal length mm, 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=111+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.
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
Note
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=81+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.
思路分析:
我自己做这题的疑惑点:首先是,如何求两个字符串之间的差值,是转化类型还是直接相减?其次就是,多个串是怎么相减,要用循环,怎么用?
针对:如何求两个字符串之间的差值,采取定义字符串数组进行直接相减,针对疑惑点,首先,我们是定义一个字符串数组,然后把他的相邻两个子项进行相减,同时定义一个自定义函数cost,通过把相邻子项的每一个子项,此时为一个个字符,进行相减,同时定义一个临时变量,用来保存差的和。
我的题意理解错了,是采取两两相减,差的比大小,取最小。印次1,采用min函数进行两两比较,首先第一次比较,只存在一个相减的结果,因此,定义一个整数类型最大数INT_MAX.把二者结果,毫无疑问是cost(s[i],s[i+1])与下一个进行比较,直到循环结束,比出来的为最小。
注意:
自定义函数cost内需要取绝对值操作,因为并不知道a[i]与b[i]哪一个数大。
后面ans=要调用min函数,因为多重循环后可以实现所有相邻二者差哪一个最小的操作。
代码实现:
#include<bits/stdc++.h>
using namespace std;
int cost(string &a,string &b){
int val=0;
for(int i=0;i<a.size();i++){
val+=abs(b[i]-a[i]);//取绝对值,差值可能为负数。
}
return val;
}
int main(){
int t;
for(cin>>t;t;t--){
int n,m;
cin>>n>>m;
vector<string> s(n);
for(int i=0;i<n;i++)cin>>s[i];
int ans=INT_MAX;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
ans=min(ans,cost(s[i],s[j]));/*min函数不要忘,
取二者最小,循环后相当于两者之间最小 */
}
}
cout<<ans<<endl;
}
return 0;
}
运行结果: