字串变换(BFS,STL)

在这里插入图片描述
在这里插入图片描述
分析:很明显用搜索来做,将每种规则装入数组中,去搜索每种变换,直到找到需要的字符串为止,我这里是用BFS来解决的。

这里有一个坑点:在我们需要改变原始字符串是,不能用替换,否则原始字符串改变会影响其他变换规则的变换,这里我们只能使用拼接压入队列中

#include<cstdio>
#include<string>
#include<map>
#include<iostream>
#include<queue>
#include<map>
using namespace std;
map<string,string>mp;
int main(){
	string A,B;
	string x[10],y[10];//记录起始,与结束的状态 
	cin>>A>>B; 
	int n=1;
	while(cin>>x[n]>>y[n]){//将规则存入数组当中 
		n++;
	}
	n--;
	queue<string>A0;//起始状态压入队列 
	queue<int>p;
	A0.push(A);
	p.push(0);
	while(!A0.empty()){
		//cout<<A0.front()<<p.front()<<endl;
		if(A0.front()==B){//当找到时输出 
			cout<<p.front();
			return 0; 
		}
		if(p.front()==10){//当次数大于10次直接弹出不需要继续搜索 
			A0.pop();
			p.pop();
		}
		string t=A0.front();;
	    if(mp.count(t)){//检测当前字符串有没有出现过 
	    	A0.pop();
	    	p.pop();
	    	continue;
	    }
	    mp[t]=1;
		for(int i=1;i<=n;i++){//依次按规则作出几种变换 
			int L=0;
			while(t.find(x[i],L)!=-1){//如果找得到 
				L=t.find(x[i],L);
				//A0.push(t.replace(L,x[i].length(),y[i]));
				A0.push(t.substr(0,L)+y[i]+t.substr(L+x[i].length()));//改变字符串压入队里中 
				p.push(p.front()+1);//次数加一 
				//cout<<t<<" "<<p.front()<<endl;
				L++;
			}
		} 
		A0.pop();//当前字符串完成了任务 
		p.pop();
	}
	printf("NO ANSWER!\n");

	return 0;
} 

我还有一种写法,将规则存成映射关系,但是只能AC百分之60的数据
希望有人指正

#include<cstdio>
#include<string>
#include<map>
#include<iostream>
#include<queue>
#include<set>
using namespace std;
int main(){
    string A,B;
    string x,y;
    cin>>A>>B;
    map<string,string>s;
    set<string>pp; 
    while(cin>>x>>y){
        s[x]=y;
    }
    queue<string>A0;
    queue<int>p;
    A0.push(A);
    p.push(0);
    while(!A0.empty()){
        if(A0.front()==B){//当找到时输出 
            cout<<p.front();
            return 0; 
        }
        if(p.front()>=10){
            A0.pop();
            p.pop();
        }
        int kai,len=0;
        string t=A0.front();
        if(pp.count(t)){
        	A0.pop();
        	p.pop();
        	continue;
        }
        pp.insert(t);
        map<string,string>::iterator it;
        for(it=s.begin();it!=s.end();it++){
            if(t.find(it->first,0)!=-1){
            	kai=t.find(it->first,0);
                len=it->first.size();
                //t.replace(kai,len,it->second);
                //cout << kai << len <<it->first<<" "<< it->second << endl;
                A0.push(t.substr(0,kai)+it->second+t.substr(kai+len));
                p.push(p.front()+1);
            }
        }
        A0.pop();
        p.pop();
    }
    printf("NO ANSWER!\n");
 
    return 0;
} 
发布了160 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Anterior_condyle/article/details/104774778