codevs1099 字串变换

题目描述 Description

已知有两个字串 A$, B$ 及一组字串变换的规则(至多6个规则):
     A1$ -> B1$
     A2$ -> B2$
  规则的含义为:在 A$中的子串 A1$ 可以变换为 B1$、A2$ 可以变换为 B2$ …。
    例如:A$='abcd' B$='xyz'
  变换规则为:
    ‘abc’->‘xu’ ‘ud’->‘y’ ‘y’->‘yz’

  则此时,A$ 可以经过一系列的变换变为 B$,其变换的过程为:
   ‘abcd’->‘xud’->‘xy’->‘xyz’

  共进行了三次变换,使得 A$ 变换为B$。

输入描述 Input Description

输入格式如下:

   A$ B$
   A1$ B1$
   A2$ B2$  |-> 变换规则
   ... ... / 
  所有字符串长度的上限为 20。

输出描述 Output Description

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

样例输入 Sample Input

abcd xyz
abc xu
ud y
y yz

样例输出 Sample Output

3

 
#include<bits/stdc++.h>
using namespace std;
struct Node{string s;int step;};
map<string,bool> use;
string s,t,R[21][2];
queue<Node> q;
int n;
int bfs(string s){
	q.push((Node){s,0});
	while(!q.empty()){
		Node u=q.front(); q.pop();
		if(u.s==t)return u.step;
		for(int i=0;i<u.s.size();i++)
			for(int j=1;j<=n;j++){
				Node v=u;
				if(!u.s.compare(i,R[j][0].length(),R[j][0])){	
					v.s.replace(i,R[j][0].length(),R[j][1]); v.step++;
					if(!use[v.s] && v.step<=10){use[v.s]=true; q.push(v);}
				}
			}
	}
	puts("NO ANSWER!");
	exit(0);
	return 0;
}

int main(){
	n=1;
	cin>>s>>t;
	while(cin>>R[n][0]>>R[n][1])n++;
	n--;
	printf("%d
",bfs(s));
	return 0;
}
原文地址:https://www.cnblogs.com/codetogether/p/7066558.html