【题解】洛谷P1032[NOIP2002]字串变换 字符串+bfs

题目链接
在这里插入图片描述
在这里插入图片描述


参考了大佬题解
安利大佬博客,好感动惹qwq

#include<cstdio>
#include<iostream>
#include<queue>
#include<map>
using namespace std;
string a,b,st[10],ed[10];
int cnt;
map<string,int>mp;
struct node{
	string s;
	int step;
	node(){}
	node(string _s,int _step):s(_s),step(_step){}
};
string translate(string s,int i,int j)
{
	string ans="";
	if(i+st[j].length()>s.length())return ans;
	for(int k=0;k<st[j].length();k++)
	    if(s[i+k]!=st[j][k])return ans;
	ans=s.substr(0,i);
	ans+=ed[j];
	ans+=s.substr(i+st[j].length());
	return ans;
}
void bfs()
{
	queue<node>q;q.push(node(a,0));int ans=0;
	while(q.size())
	{
		node tmp=q.front();q.pop();
		string temp;
		if(mp[tmp.s]==1)continue;
		if(tmp.s==b){ans=tmp.step;break;}
		mp[tmp.s]=1;
		for(int i=0;i<tmp.s.length();i++)
		    for(int j=0;j<cnt;j++)
		    {
		    	temp=translate(tmp.s,i,j);
		    	if(temp!="")q.push(node(temp,tmp.step+1));
			}
	}
	if(ans>10||ans==0)cout<<"NO ANSWER!\n";
	else cout<<ans<<endl;
}
int main()
{
	//freopen("in.txt","r",stdin);
	cin>>a>>b;
	while(cin>>st[cnt]>>ed[cnt])cnt++;
	bfs();
	return 0;
}

总结

字符串操作与bfs的结合,好题。

猜你喜欢

转载自blog.csdn.net/qq_41958841/article/details/83245472
今日推荐