UVa 429 - Word Transformation

題目:單詞變換,每次可以變化一個字母,已知一個單詞列表、初始單詞、終止單詞,

            確定從初始單詞到終止單詞的最少變化步數。

分析:圖論、最短路。可以變化記為距離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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值