題目:單詞變換,每次可以變化一個字母,已知一個單詞列表、初始單詞、終止單詞,
確定從初始單詞到終止單詞的最少變化步數。
分析:圖論、最短路。可以變化記為距離1,然後利用floyd求解,查表輸出。
說明:╮(╯▽╰)╭。
#include <cstdio>
#include <cstring>
char dictionary[202][11];
int path[202][202];
int get_id(char str[], int size)
{
for (int i = 0; i < size; ++ i) {
if (!strcmp(str, dictionary[i])) {
return i;
}
}
return -1;
}
int main()
{
int t;
char buf[25], from[11], to[11];
scanf("%d", &t);
getchar();
getchar();
while (t --) {
int size = 0;
while (gets(dictionary[size]) && strcmp(dictionary[size], "*")) {
size ++;
}
// create dist matrix
for (int i = 0; i < size; ++ i) {
for (int j = i; j < size; ++ j) {
int count = 0;
for (int k = 0; dictionary[i][k]; ++ k) {
count += (dictionary[i][k] != dictionary[j][k]);
}
if (count <= 1) {
path[i][j] = path[j][i] = 1;
}else {
path[i][j] = path[j][i] = 202;
}
}
}
// floyd
for (int k = 0; k < size; ++ k) {
for (int i = 0; i < size; ++ i) {
for (int j = 0; j < size; ++ j) {
if (path[i][j] > path[i][k]+path[k][j]) {
path[i][j] = path[i][k]+path[k][j];
}
}
}
}
while (gets(buf) && buf[0]) {
sscanf(buf, "%s%s", from,to);
int begin = get_id(from, size);
int end = get_id(to, size);
printf("%s %s %d\n", from, to, path[begin][end]);
}
if (t) {
puts("");
}
}
return 0;
}