题目大意
给出一对字符串s,c,然后给出多对字符串s1, c1…sn, c1。可以使s中的si字串转化为ci,问是否能在十次以内将s字符串转化为c字符串。
初步想法
因为这道题就是一个字符串s中的子串不停的被转换,直到变成c,所以我们可以模拟一遍他换的过程。也就是说,我们每遇到一个s中si子串,我们就进行替换,这个过程就有点像广搜,因为每一次替换都可能指向最终结果。
优化
因为是广搜,所以一直搜下去会有很多很多种情况,所以我们要合理剪枝。因为题目要求要在十次以内将s转换为c,所以我们可以记录每一次转换后所构成字符串的转换次数,一旦超过了十次,我们直接就结束搜索。
PS(每次寻找子串都是通过string中的find()函数寻找的)
上代码!!!
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<map>
#define ll long long
#define pi acos(-1)
#define inf 0x3f3f3f3f
#define pii pair<int, int>
#define psi pair<string, int>
#define piii pair<pii, int>
#define mp(a, b) make_pair(a, b)
#define min(a, b) (a < b ? a : b)
#define max(a, b) (a > b ? a : b)
#define ufor(a, b, i) for (register int i = (a); i <= (b); ++i)
#define dfor(a, b, i) for (register int i = (a); i >= (b); --i)
using namespace std;
inline ll read() {
ll x = 0, f = 1;
char ch = getchar();
while(ch < '0' || ch > '9') {
if(ch == '-') f = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9') {
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
const int N = 303;
string str[10][2], A, B;
map<string, int> m;
int cnt;
queue<psi> q;
psi p;
void bfs() {
q.push(mp(A, 0));
while (!q.empty()) {
p = q.front();
if (p.second >= 10) {
printf("NO ANSWER!\n");
return ;
}
if (p.first == B) {
printf("%d\n", p.second);
return ;
}
if (m[p.first]) {
q.pop();
continue;
}
m[p.first] = 1;
ufor(0, cnt-1, i) {
int pos = 0;
while (pos = p.first.find(str[i][0], pos), pos != -1) {
string s = p.first;
s.replace(pos, str[i][0].length(), str[i][1]);
q.push(mp(s, p.second+1));
pos++;
}
}
q.pop();
}
printf("NO ANSWER!\n");
return ;
}
int main() {
cin >> A >> B;
while (cin >> str[cnt][0] >> str[cnt++][1]);
bfs();
return 0;
}