80分求助
查看原帖
80分求助
1040409
dhpzy楼主2023/10/20 21:48
#include<bits/stdc++.h>
using namespace std;
string x,y,a[10001],b[10001];
int n,minn=INT_MAX;
map<string,bool>m;
int bfs(string s,string s1)
{
	queue<string>q1;
	queue<int>q2;
	q1.push(s);
	q2.push(0);
	while(!q1.empty()&&q2.front()<=10)
	{
		if(m[q1.front()])
		{
			q1.pop();
			q2.pop();
			continue;
		}
		m[q1.front()]=1;
		string xx=q1.front();
		q1.pop();
		for(int i=1;i<=n;i++)
		{
			int w=xx.find(a[i]);
			if(w==-1) continue;
			string yy=xx;
			yy.replace(w,a[i].size(),b[i]);
			q1.push(yy);
			q2.push(q2.front()+1);
			if(yy==s1&&q2.front()+1<=10) return q2.front()+1;
		}
		q2.pop();
	}
	return -1;
}
int main()
{
	cin>>x>>y;
	string q,w;
	int tt;
	cin>>tt;
	m.clear();
	while(tt--)
	{
		cin>>q>>w;
		n++;
		a[n]=q;
		b[n]=w;
	}
	minn=bfs(x,y);
	if(minn==-1) cout<<"NO ANSWER!";
	else cout<<minn;
}
/*abaaaba abcdaba
6
a b
b d
d e
e f
f g
g c
*/
//8
2023/10/20 21:48
加载中...