练习codeforces1676C. Most Similar Words
题目如下
链接https://codeforces.com/problemset/problem/1676/C
C. Most Similar Words
time limit per test2 seconds
memory limit per test256 megabytes
You are given 𝑛 words of equal length 𝑚, consisting of lowercase Latin alphabet letters. The 𝑖-th word is denoted 𝑠𝑖.
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 𝑠𝑖 and 𝑠𝑗 such that (𝑖<𝑗). In other words, find the minimum difference over all possible pairs of the 𝑛 words.
Input
The first line of the input contains a single integer 𝑡 (1≤𝑡≤100) — the number of test cases. The description of test cases follows.
The first line of each test case contains 2 integers 𝑛 and 𝑚 (2≤𝑛≤50, 1≤𝑚≤8) — the number of strings and their length respectively.
Then follows 𝑛 lines, the 𝑖-th of which containing a single string 𝑠𝑖 of length 𝑚, 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.
题目大意
对题目给定的字符串进行合法操作,操作如下
字符串中的字符每次向后移,如‘a' => 'b' 记作一次操作,
在每组测试样例中,找出操作最少的一组以使得一个字符串与另一个字符串完全等同
使用类型为char的二维数组,例如char[i[[j],
分别表示第i个字符串和第i个字符串中的第j个字符
对每组的字符串两两进行比较,找出相差最小即所需操作次数最少的字符串,再累计操作次数
点击查看代码
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++){
int diff = 0;
for (int k = 0; k < l; k++){
diff += abs(s[i][k] - s[j][k]);
}
if(diff < min)
min = diff;
}
}
完整代码
点击查看代码
#include <stdio.h>
#include <cmath>
char s[55][10];
int main(){
int t;
scanf("%d",&t);
while(t--){
int n,l;
scanf("%d%d",&n,&l);
for (int i = 0; i < n; i++){
scanf("%s", s[i]);
}
int min = 1e9;
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++){
int diff = 0;
for (int k = 0; k < l; k++){
diff += abs(s[i][k] - s[j][k]);
}
if(diff < min)
min = diff;
}
}
printf("%d\n",min);
}
return 0;
}

浙公网安备 33010602011771号