题意
样例
样例输入:
样例一
abcd xyz
abc xu
ud y
y yz
样例二
abaaaba abcdaba
a b
b d
d e
e f
f g
g c
样例输出:
样例一
3
样例二
8
思路
1.可以把每一个过程中的字串抽象为一个点,然后变换的条件抽象成边.
2.从初始字串s开始,从1到n枚举变换规则
如果s中含有变换前的字串from[i] 就使用该规则 (注意判断变换后的字串是否已经到达过)
(此处还要注意 有可能当前的字串不止包含from[i]一次 因此我们用while循环 将字串中所有可变换的都枚举出来)
3.注意剪枝 当当前点dis已经超过10 就continue掉
其余都是BFS的部分 见代码
总结
第一次80分 没想起来一个字串可以包含多个from[i] 下载了第五个点才知道 将if改成while才行
代码
#include<iostream>
#include<string.h>
#include<string>
#include<algorithm>
#include<math.h>
#include<queue>
#include<map>
using namespace std;
string s,t;
string from[10],to[10];
queue<string> q;
map<string,int> dis;
int n;
void bfs()
{
dis[s]=0;
q.push(s);
while(!q.empty())
{
string now=q.front(),tmp=" ";q.pop();
if(dis[now]>10) continue;;
if(now==t) break;
for(int i=1;i<=n;i++)
{
int pos=now.find(from[i],0);
while(pos!=string::npos)//当前串有该子串
{
tmp=now;
tmp.replace(pos,from[i].size(),to[i]);
if(dis.find(tmp)==dis.end()) //当前子串状态还没有到达过
{
dis[tmp]=dis[now]+1;
q.push(tmp);
}
pos=now.find(from[i],pos+1);
}
}
}
if(dis.find(t)==dis.end()||dis[t]>10) cout<<"NO ANSWER!"<<endl;
else cout<<dis[t]<<endl;
}
int main()
{
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
cin>>s>>t;
while(cin>>from[++n]>>to[n]) ;
n--;
if(s==t) cout<<0<<endl;
else bfs();
return 0;
}