a614中等字母替換隱含圖與 BFS 路徑還原
CPE:Doublets (UVa 10150)
只產生相差一字母的鄰居,搜尋最短 doublet 序列。
解題思路
把每個字典單字當頂點,恰一位置不同時有邊。無須兩兩比較整本字典;擴展單字時枚舉每個位置及 a–z 的替換,若新字在字典中便是鄰居。這只會連到等長單字,避免不必要的圖建構。
每個查詢使用 BFS,首次到達一字時保存其前驅;BFS 按距離分層,因此第一次到達終點時得到最短序列。從終點沿前驅回到起點再反轉輸出。字典由第一個空行終止;查詢間恰留一空行,無解印 No solution.。原題允許任一最短序列,本地公開資料採唯一解或無解。
Step-by-step animation
示意:字典 cat、cot、cog、dog,查 cat 到 dog
步驟 1 / 3
起點層
cat 距離 0,替換 a 為 o 可到 cot。
cat:0
cot:1
- parent(cot)
- cat
- 距離
- 1
#include <algorithm>
#include <iostream>
#include <queue>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
int main() {
unordered_set<string> dict;
string line;
while (getline(cin, line)) {
if (!line.empty() && line.back() == '\r')
line.pop_back();
if (line.empty())
break;
dict.insert(line);
}
string start, goal;
bool first = true;
while (cin >> start >> goal) {
if (!first)
cout << '\n';
first = false;
unordered_map<string, string> parent;
queue<string> q;
if (dict.count(start) && dict.count(goal)) {
parent[start] = start;
q.push(start);
}
while (!q.empty() && !parent.count(goal)) {
string u = q.front();
q.pop();
string v = u;
for (int i = 0; i < (int)u.size(); ++i) {
for (char ch = 'a'; ch <= 'z'; ++ch) {
v[i] = ch;
if (dict.count(v) && !parent.count(v)) {
parent[v] = u;
q.push(v);
}
}
v[i] = u[i];
}
}
if (!parent.count(goal)) {
cout << "No solution.\n";
continue;
}
vector<string> path;
string v = goal;
for (;;) {
path.push_back(v);
if (v == start)
break;
v = parent[v];
}
reverse(path.begin(), path.end());
for (auto &w : path)
cout << w << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。