luogu1032:字串转换:宽搜+string

题目连接:该题是luogu试炼场的2-8:T2


题目大意:
1 给出开始串和目标串;
2 有n种变化方法,开始穿的部分子串,可以从a形式变成b形式;
3 请问:开始串能否在10次变化内,到达目标串;


解题思路:内核是宽搜的元问题,但是要用到字符串的处理
1 字符串处理的元问题,因为涉及到字符串的判断,查找,替换等问题;
2 本题题解用了string类来简化代码量:
3 关于string类型的解说:
https://blog.csdn.net/fdqw_sph/article/details/54233971
https://www.cnblogs.com/zpcdbky/p/4471454.html


上代码:
 

//luogu1032:字串转换 
//字符的转化问题 

//讲解stl:string 
//https://blog.csdn.net/fdqw_sph/article/details/54233971
//https://www.cnblogs.com/zpcdbky/p/4471454.html

//要求只需要变10次,10次以外可以忽略 

#include<bits/stdc++.h>
using namespace std;

string st,ed;
string a[10],b[10];
struct nod{ string s;int t;} f[2000005];
int n;//n种变换方法 

void inp()//输入处理 
{
	cin>>st>>ed;
	n=1;
	while(cin>>a[n]>>b[n])	n++;
	n--;
} 

void bfs()
{
	int tou=1,wei=2;
	f[tou].s=st;
	f[tou].t=0;
	while(tou<wei)
	{
		if(f[tou].t>10) //步数超限 
		{
			cout<<"NO ANSWER!"<<endl;
			exit(0);
		}
		
		for(int i=1;i<=n;i++)
		{
			string x=f[tou].s;
			int t=x.find(a[i]);//查找a[i]在x中第一次出现的位置
			
			while(1)
			{
				if(t==-1) break;//x里没有a[i]
				
				//x里有a[i] 
				f[wei].s=f[tou].s;
				f[wei].t=f[tou].t+1;
				//replace:
				//在x中:从t开始,a[i].size()的长度,用b[i]替代 
				f[wei].s.replace(t,a[i].size(),b[i]);
				
				if(f[wei].s==ed)
				{
					cout<<f[wei].t;
					exit(0);
				}
				wei++;
				t=x.find(a[i],t+1);//查找x中下一个可替换的位置 
			} 
		} 
		
		tou++;
	}
}

int main()
{
	inp();//输入处理 
	
	bfs();
	
	return 0;
	
}

猜你喜欢

转载自blog.csdn.net/liusu201601/article/details/89154400