题目:
题解:
普及STL用法+string系列
代码:
#include <cstdio>
#include <string>
#include <queue>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
struct node{int num; string a; node(int num,string a):num(num),a(a){}};
vector< pair<string,string> > v;
set <string> repe;
//map <string,int> repe;
string A,B;
bool bfs()
{
queue<node>q;
q.push(node(0,A));
while (!q.empty())
{
node now=q.front(); q.pop();
if (now.num>10) return 0;
for (int i=0;i<v.size();i++)
if (now.a.find(v[i].first)!=-1)
for (int j=now.a.find(v[i].first);j<now.a.length();j=now.a.find(v[i].first,j+1)) //这个串里有子串(不知几个),一次一次往下找
{
string t=now.a;
t.replace(j,v[i].first.length(),v[i].second);
if (t==B) {printf("%d",now.num+1);return 1;}
if (!repe.count(t))
{
q.push(node(now.num+1,t));
repe.insert(t);
}
}
}
return 0;
}
int main()
{
cin>>A>>B;
string a,b;
while (cin>>a>>b) v.push_back(make_pair(a,b));
if (!bfs()) printf("NO ANSWER!");
}