#include <cstring>
#include <string>
#include <cstdio>
#include <map>
#include <queue>
#include <vector>
using namespace std;
const int N = 20;
const int M = 25500;
const int INF = 0x3f3f3f3f;
struct Edge
{
int from, to, w;
};
struct HeapNode
{
int d, u;
bool operator < (const HeapNode &other) const
{
return d > other.d;
}
};
map<string, int> strMap;
map<int, string> intMap;
int cnt;
vector<string> dict;
vector<Edge> vecEdge;
vector<int> adjList[M];
int d[M], p[M];
bool vis[M];
bool ok(const string &s1, const string &s2);
void addEdge(int u, int v, int w);
void dijkstra(int s, int t);
int main()
{
static char buf[N], buf2[N];
string word;
string source, dest;
int kase = 1;
cnt = 0;
#ifndef ONLINE_JUDGE
freopen("e:\\uva_in.txt", "r", stdin);
#endif
while (gets(buf)) {
word = buf;
if (word == "") break;
if (!strMap.count(word)) {
strMap[word] = cnt;
intMap[cnt] = word;
cnt++;
for (size_t i = 0; i < dict.size(); i++) {
if (ok(dict[i], word)) {
int u = strMap[dict[i]];
int v = strMap[word];
addEdge(u, v, 1);
}
}
dict.push_back(word);
}
}
while (scanf("%s%s", buf, buf2) == 2) {
if (kase != 1) printf("\n");
kase++;
source = buf, dest = buf2;
if (source.length() != dest.length()) {
printf("No solution.\n");
continue;
}
int s = strMap[source];
int t = strMap[dest];
dijkstra(s, t);
}
return 0;
}
bool ok(const string &s1, const string &s2)
{
if (s1.size() != s2.size()) return false;
int cnt = 0;
for (size_t i = 0; i < s1.length(); i++) {
if (s1[i] != s2[i]) cnt++;
if (cnt > 1) return false;
}
return cnt == 1;
}
void addEdge(int u, int v, int w)
{
vecEdge.push_back((Edge){u, v, w});
vecEdge.push_back((Edge){v, u, w});
int size = vecEdge.size();
adjList[u].push_back(size - 2);
adjList[v].push_back(size - 1);
}
void dijkstra(int s, int t)
{
priority_queue<HeapNode> pq;
for (int i = 0; i < cnt; i++) {
d[i] = (i == s ? 0 : INF);
p[i] = -1;
vis[i] = false;
}
pq.push((HeapNode){d[s], s});
while (!pq.empty()) {
HeapNode node = pq.top(); pq.pop();
int u = node.u;
if (u == t) break;
if (vis[u]) continue;
vis[u] = true;
for (size_t i = 0; i < adjList[u].size(); i++) {
int &e = adjList[u][i];
int v = vecEdge[e].to;
int w = vecEdge[e].w;
if (d[u] + w < d[v]) {
d[v] = w + d[u];
p[v] = u;
pq.push((HeapNode){d[v], v});
}
}
}
if (d[t] == INF) {
printf("No solution.\n");
} else {
static int ans[M];
int top = 0;
while (t != -1) {
ans[top++] = t;
t = p[t];
}
for (int i = top - 1; i >= 0; i--) {
printf("%s\n", intMap[ans[i]].c_str());
}
}
}
UVa10150Problem B: Doublets
最新推荐文章于 2020-02-19 15:43:46 发布