Subject address:
https://www.acwing.com/problem/content/description/192/
There are two known strings AAA, B B B and a set of string conversion rules (at most6 66 rules):
A 1 → B 1 A_1→B_1A1→B1
A 2 → B 2 A_2→B_2 A2→B2
… … …
The meaning of the rule is: inAAA in substringA 1 A_1A1Can be converted to B 1 B_1B1、 A 2 A_2 A2Can be transformed into B 2… B_2…B2... .
For example: theA=abcd B=xyz
conversion rule is:
abc → xu, ud → y, y → yz
then at this time,AAA can be transformed intoBBthrough a series of transformationsB , the transformation process is:
"abcd → xud → xy → xyz"
a total of three transformations are carried out, so thatAAA is converted toBBB。
Input format: The
input format is as follows:
A BA\ BA B
A 1 B 1 A_1 \ B_1A1 B1
A 2 B 2 A_2\ B_2 A2 B2
… … … … ……The
first line is two given stringsAAA andBBB . The next few lines, each line describes a set of string transformation rules. The maximum length of all strings is20 2020。
Output format:
if in 10 10. 1 0 Step (containing10 101 0 step) can withinAAA is converted toBBB , then output the least number of transformation steps; otherwise, outputNO ANSWER!
.
Two-way BFS can be used. Every time you consider dequeuing, you can expand the queue with fewer elements first. code show as below:
#include <iostream>
#include <queue>
#include <unordered_map>
using namespace std;
const int N = 6;
int n;
string a[N], b[N];
int res;
// 返回从q的队头拓展出一步是否会和和另一个方向“会师”
bool extend(queue<string>& q, unordered_map<string, int>& da, unordered_map<string, int>& db, string a[], string b[]) {
string t = q.front();
q.pop();
// 枚举从t的哪个位置开始变换
for (int i = 0; i < t.size(); i++)
// 枚举是否能变换,当能变换的时候,求一下能变为谁
for (int j = 0; j < n; j++)
if (t.substr(i, a[j].size()) == a[j]) {
string ne = t.substr(0, i) + b[j] + t.substr(i + a[j].size());
// 如果之前走到过这个状态,则略过
if (da.count(ne)) continue;
// 否则更新一下距离
da[ne] = da[t] + 1;
// 如果与另一边会师了,则记录一下答案,并返回true
if (db.count(ne)) {
res = da[ne] + db[ne];
return true;
}
q.push(ne);
}
return false;
}
int bfs(string A, string B) {
unordered_map<string, int> da, db;
da[A] = db[B] = 0;
queue<string> qa, qb;
qa.push(A), qb.push(B);
while (qa.size() && qb.size()) {
if (qa.size() <= qb.size()) {
if (extend(qa, da, db, a, b)) return res;
} else if (extend(qb, db, da, b, a)) return res;
}
return 11;
}
int main() {
string A, B;
cin >> A >> B;
while (cin >> a[n] >> b[n]) n++;
int res = bfs(A, B);
if (res > 10) cout << "NO ANSWER!" << endl;
else cout << res << endl;
return 0;
}
Time complexity O (V + E) O(V+E)O ( V+E)。