洛谷P1032 字串变换(BFS+STL字符串处理)
题目描述
已知有两个字串 A,BA,B 及一组字串变换的规则(至多 66 个规则):
A1 -> B1
A2 -> B2
规则的含义为:在 AA 中的子串 A1 可以变换为 B1 , A2 可以变换为 B2 …。
例如: A =' abcd ' BB =' xyz '
变换规则为:
‘ abc ’->‘ xu ’‘ ud ’->‘ y ’‘ y ’->‘ yz ’
则此时, A 可以经过一系列的变换变为 B ,其变换的过程为:
‘ abcd ’->‘ xud ’->‘ xy ’->‘ xxyz ’
共进行了 3 次变换,使得 A 变换为 B 。
输入格式
输入格式如下:
A BA1 B1A2 B2 |-> 变换规则
... ... /
所有字符串长度的上限为 20 。
输出格式
输出至屏幕。格式如下:
若在 10 步(包含 10 步)以内能将 A 变换为 B ,则输出最少的变换步数;否则输出"NO ANSWER!"
输入样例
abcd xyzabc xuud yy yz
输出样例
3
思路
string类型存各个输入数据
用BFS搜索多种规则,一旦匹配,替换成新字符串后入队。
判断匹配用的是string.find() ,替换用repalce() ,判重用map 映射当前字符串是否已经出现过。
注意
先替换再判断替换后的字符串是否已经出现过,顺序不能反
待替换字符串可能存在多个符合替换规则的子串,所以要让字符串中每个字符都当一次起点进行find(目标,起点)
不能直接对队列顶替换,否则影响其他替换规则的搜索,要用临时变量存队列顶的结构体元素,再对临时变量替换并入队
代码
#include<bits/stdc++.h>
using namespace std;
string A,B,before[10],after[10];
int n;
map<string,int> vis;//判重
struct shit
{
int step;
string s;
}S,T,top,newStr,temp;
int reFind;
int BFS()
{
queue<shit> q;
q.push(S);
while(!q.empty())
{
top=q.front();
q.pop();
if(top.step>10)//超时
{
return -1;
}
if(top.s==T.s)//找到
{
return top.step;
}
for(int i=1;i<=n;i++)
{
reFind=-1;
while(++reFind<=top.s.length())//以每个字符串为起点
{
if(top.s.find(before[i],reFind)!=string::npos)//找字串
{
temp=top;
newStr.s=temp.s.replace(temp.s.find(before[i],reFind),before[i].length(),after[i]);
if(vis[newStr.s]==1) continue;//重复
newStr.step=temp.step+1;
q.push(newStr);
vis[newStr.s]=1;
}
}
}
}
return -1;
}
int main()
{
cin>>A>>B;
S.s=A;S.step=0;
T.s=B;
n=1;
while(cin>>before[n]>>after[n])
{
n++;
}
n--;
int ans=BFS();
if(ans==-1) cout<<"NO ANSWER!";
else cout<<ans;
return 0;
}