P1032. 字串变换

考点

  • BFS
  • 字符串
  • 哈希表
  • 双向BFS

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <bits/stdc++.h>
using namespace std;
const int maxn = 6;
int n;
string a, b, k[maxn], v[maxn];
unordered_map<string, int> astep, bstep;
queue<string> aq, bq;

int f(queue<string> &aq, queue<string> &bq, unordered_map<string, int> &astep,
unordered_map<string, int> &bstep, string k[], string v[]) {
int sz = aq.size(), as = astep[aq.front()], bs = bstep[bq.front()];
while (sz--) {
string u = aq.front();
aq.pop();
for (int i = 0; i < n; ++i) {
string p = k[i];
for (int j = 0; j < u.length(); ++j) {
if (u.substr(j, p.length()) == p) {
string t = u.substr(0, j) + v[i] + u.substr(j + p.length());
if (bstep.count(t)) return as + bs + 1;
if (bstep.count(t)) continue;
astep[t] = astep[u] + 1;
aq.emplace(t);
}
}
}
}
return 11;
}

int bfs() {
int res, cnt = 0;
if (a == b) return 0;
astep[a] = 0, bstep[b] = 0;
aq.emplace(a), bq.emplace(b);
while (!aq.empty() && !bq.empty()) {
if (aq.size() <= bq.size()) {
res = f(aq, bq, astep, bstep, k, v);
} else {
res = f(bq, aq, bstep, astep, v, k);
}
if (res <= 10) return res;
if (++cnt == 10) break;
}
return -1;
}

int main() {
string x, y;
cin >> a >> b;
// 不能用哈希表存储映射,因为会有重复键
while (cin >> x >> y) k[n] = x, v[n] = y, ++n;
int res = bfs();
if (~res) {
cout << res << endl;
} else {
cout << "NO ANSWER!" << endl;
}
return 0;
}

思路

双向BFS板子题。

有几个注意点,其余直接看代码就行:

  • 每次的新状态是只换一处匹配点,而不是全换

    比如有规则abc -> xu,字符串abcabc,那么xuabc就是新状态,abcxu是另一个新状态

  • 用哈希表记录每种字符串是否出现过 + 步数,避免死循环

  • 不能用哈希表存储映射,因为会有重复键