洛谷P1032 字串变换(bfs) 题解

题目来源:

点击打开链接

题目描述:

题目描述

已知有两个字串 A,BA,B 及一组字串变换的规则(至多 66 个规则):

A_1A1 -> B_1B1

A_2A2 -> B_2B2

规则的含义为:在 AA 中的子串 A_1A1 可以变换为 B_1B1 , A_2A2 可以变换为 B_2B2 …。

例如: AA =' abcdabcd ' BB =' xyzxyz '

变换规则为:

‘ abcabc ’->‘ xuxu ’‘ udud ’->‘ yy ’‘ yy ’->‘ yzyz ’

则此时, AA 可以经过一系列的变换变为 BB ,其变换的过程为:

‘ abcdabcd ’->‘ xudxud ’->‘ xyxy ’->‘ xyzxyz ’

共进行了 33 次变换,使得 AA 变换为 BB 。

输入输出格式

输入格式:

输入格式如下:

AA BB
A_1A1 B_1B1
A_2A2 B_2B2 |-> 变换规则

... ... /

所有字符串长度的上限为 2020 。

输出格式:

输出至屏幕。格式如下:

若在 1010 步(包含 1010 步)以内能将 AA 变换为 BB ,则输出最少的变换步数;否则输出"NO ANSWER!"

输入输出样例

输入样例#1:  复制
abcd xyz
abc xu
ud y
y yz
输出样例#1:  复制
3







解题思路:

   本题就是一个bfs,但是由于是字符串变换,在使用规则的时候注意,一个单词可能在不同位置使用同一个规则,就要考虑到,所以要枚举每一个位置和每一种规则来进行搜索,在实现上还是借鉴了大神的代码。。。。

代码:


#include <iostream>
#include <cstring>
#include <queue>
#include <string>
#include <map>
using namespace std;
map<string,int>m;
struct newt{
	string x;
	int time;
}dian;
priority_queue<newt>q;
bool operator <(newt a,newt b)
{
	return a.time>b.time;
}
string jh[10][2];
string trans(const string &str,int i,int j){//借鉴了stdcall大爷的思想
    string ans = "";
    if (i+jh[j][0].length() > str.length())
        return ans;


    for (int k=0; k < jh[j][0].length();k++)
        if (str[i+k] != jh[j][0][k])
            return ans;


    ans = str.substr(0,i);
    ans+=jh[j][1];
    ans+=str.substr(i+jh[j][0].length());
    return ans;
}
int main()
{
	string a,b;
	
	cin>>a>>b;
	int t=1;
	while(cin>>jh[t][0]>>jh[t][1])
	{
		t++;
	}
//	for(int i=1;i<=3;i++)
//	cout<<th[i][0]<<" "<<th[i][1]<<endl;
	dian.x=a;
	dian.time=0;
    q.push(dian);
    m[dian.x]=1;
    int min;
    while(!q.empty())
    {
    	newt now=q.top();
    	if(now.x==b){
    		min=now.time;
    		break;
		}
		q.pop();
		for(int i=1;i<t;i++)
		{
			newt nod;
			string temp;
			if(now.x.find(jh[i][0])!=now.x.npos)
			{
				for (int i=0;i <now.x.length();i++)//枚举当前串所有可能位置
            	for (int j=1; j<t; j++){//枚举所有可能手段
	                temp = trans(now.x,i,j);
	                if (temp != ""&&!m[temp]){
	                    nod.x = temp;
	                    nod.time = now.time+1;
	                    q.push(nod);
	                    m[nod.x]=1;
	            	}
            	}	
			}
		}
	}
	if(min<=10)cout<<min<<endl;
	else cout<<"NO ANSWER!"<<endl;
}

猜你喜欢

转载自blog.csdn.net/qq_40400202/article/details/80959240
今日推荐