题目大意:
对于每个状态下的字符串,枚举可以替换的部分替换作为下一个新的状态。
说明/提示:
对于 100 100 100% 数据,保证所有字符串长度的上限为 20 20 20。
思路/分析:
需要注意 替换的不一定是最开始匹配的子串,替换的还可能是后面的子串,比如这组样例:
a
b
c
d
e
a
b
c
d
abcdeabcd
abcdeabcd
a
b
c
d
e
e
abcdee
abcdee
a
b
c
d
e
abcd e
abcde
替换的是后面的
a
b
c
d
abcd
abcd,所以我们在枚举某个替换规则时,我们要用一个
w
h
i
l
e
while
while 循环,配合着
f
i
n
d
find
find 函数第二个参数,从上一个子串的下一位置
i
d
x
+
1
idx + 1
idx+1 寻找,避免一直找的是第一个。
代码:
#include <bits/stdc++.h>
using namespace std;
struct node {
string str;
int step;
node(string ss, int ste) {
str = ss, step = ste;
}
};
string a, b;
pair<string, string> s[10];
int cnt, ans = 1000000;
queue<node> q;
void bfs() {
while (!q.empty()) {
node now = q.front();
q.pop();
if (now.step > 10)
continue;
if (now.str == b) {
ans = now.step;
}
for (int i = 0; i < cnt; i++) {
int idx = -1;
while (1) {
string ss = now.str;
idx = ss.find(s[i].first, idx + 1);
if (idx == -1){
break;
}
ss.replace(idx, s[i].first.size(), s[i].second);
if(ss == b){
ans = now.step + 1;
return;
}
q.push(node(ss, now.step + 1));
}
}
}
}
int main() {
cin >> a >> b;
while (cin >> s[cnt].first && cin >> s[cnt++].second);
q.push(node(a, 0));
bfs();
if(ans != 1000000){
cout << ans;
}else{
cout << "NO ANSWER!";
}
return 0;
}