落谷试炼场 P1032 字串变换

题目链接:https://www.luogu.org/problemnew/show/P1032
思路:使用bfs,遍历所有替换的情况,值得注意的一点是,对同一个字符串可能在不同位置都能替换,一开始没有考虑到这一点
c++代码:

#include <iostream>
#include <queue>
#include <string>
#include <map>


using namespace std;

const int maxn=12;

string fa[maxn],fb[maxn];
map <string,bool> mp;

struct node {
	string s;
	int x;
};
queue <node>q;

int main() {
	string sa,sb;
	cin >> sa >> sb;
	int cnt=0;
	while(cin >>fa[cnt]>>fb[cnt])cnt++;
	 node a;
	 a.s=sa;
	 a.x=0;
	 q.push(a);
	 int ans;
	 bool flag=0;
	 while(!q.empty()) {
	 	 node t=q.front();q.pop();
	 	 if(t.s==sb) {
	 	      ans=t.x;
	 	      flag=1;
			  break;	
		 }
		 if(mp.count(t.s))continue;
		 mp[t.s]=1;
		 //cout << cnt <<endl;
	 	 for(int i=0;i<cnt;i++) {
              node tq=t; 	 	 	
		   while(1) {
	 	 	 int p;
	 	 	  if((p=tq.s.find(fa[i]))!=(int)string::npos){
					node tmp=t;
					int len=fa[i].length();
					tmp.s.erase(p,len);
					tmp.s.insert(p,fb[i]);
					//if(tmp.s=="procedure")cout << p <<endl;
					tmp.x=t.x+1;
					q.push(tmp);
					tq.s[p]='/';
			  }	
			  else break;
			}
		  }
	 }
	 if(flag&&ans)
	 cout << ans<< endl;
	 else cout <<"NO ANSWER!" <<endl;                        
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值