题目链接:https://www.luogu.org/problemnew/show/P1032
题意:
给定一个原字符串和目标字符串,以及几个字符串变换的规则。
问能否根据这几个规则在十步之内把原字符串变为目标字符串。
思路:
bfs,队列维护字符串和所经过的步骤这样一个二元组而不是简单的字符串。
每一次取出一个字符串,用所给的规则进行变换得到新的字符串。
由于字符串中可能有多次匹配,所以用vector存每一次匹配的开始位置,这些都是独立的一次变换都要单独存入vector中。【这一点最开始没有考虑到,图方便用了.find()】
#include<stdio.h>
#include<stdlib.h>
#include<map>
#include<set>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue> using namespace std; string A, B;
struct rule{
string a, b;
}rules[];
struct node{
string s;
int steps;
node(){}
node(string _s, int _steps){
s = _s;
steps = _steps;
}
};
set<string>sset; int main()
{
cin>>A>>B;
int n = ;
while(cin>>rules[n].a>>rules[n].b)n++; queue<node>que;
que.push(node(A, ));
int steps = ;
bool flag = false;
while(!que.empty()){
node now = que.front();que.pop();
//cout<<now.s<<" "<<now.steps<<endl;
if(now.s == B){
flag = true;
steps = now.steps;
break;
}
if(now.steps == )continue;
for(int i = ; i < n; i++){
//cout<<i<<endl;
vector<int>pos;
//cout<<rules[i].a.length()<<endl;
//cout<<now.s.length()<<endl;
//cout<<now.s.length() - rules[i].a.length()<<endl;
for(int j = ; j < now.s.length(); j++){
bool f = true;
for(int k = ; k < rules[i].a.length(); k++){
if(j + k >= now.s.length()){
f = false;
break;
}
if(now.s[j + k] != rules[i].a[k]){
f = false;
break;
}
}
if(f)pos.push_back(j);
} //cout<<pos.size()<<endl;
for(int x = ; x < pos.size(); x++){
int p = pos[x];
char t[];
int j;
for(j = ; j < p; j++){
t[j] = now.s[j];
//cout<<t[j];
}
for(int k = ; k < rules[i].b.length(); k++, j++)
{
t[j] = rules[i].b[k];
}
for(int k = p + rules[i].a.length(); k < now.s.length(); k++, j++){
t[j] = now.s[k];
}
t[j] = '\0'; if(sset.find(t) == sset.end()){
que.push(node(t, now.steps + ));
sset.insert(t);
}
}
}
}
if(flag){
printf("%d\n", steps);
}
else{
printf("NO ANSWER!\n");
}
return ;
}
---恢复内容结束---