【搜索】P1032 字串变换

题目描述

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

A1 ->B1

A2 -> B2

规则的含义为:在 A中的子串 A1 可以变换为B1A2 可以变换为 B2 …。

例如:A='abcd'B='xyz'

变换规则为:

abc’->‘xu’‘udud’->‘y’‘y’->‘yz’

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

abcd’->‘xud’->‘xy’->‘xyz’

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

输入输出格式

输入格式:

输入格式如下:

B
A1 B1
A2 B2 |-> 变换规则

... ... /

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

输出格式:

输出至屏幕。格式如下:

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

输入输出样例

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

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int N = 10;
 4 string A,B,a[N],b[N];
 5 map<string,int>Mp;
 6 
 7 typedef struct Node{
 8     string S;
 9     int step;
10 }Node;
11 
12 int cnt = 0;
13 int Check(string u,string v,int pos = 0 ){
14     int L1 = u.length() ;
15     int L2 = v.length() ;
16     int i = pos , j = 0 ;
17     while( i < L1 && j < L2 ){
18         while( u[i] == v[j] ){
19             i++;
20             j++;
21             if( j == L2 ){
22                 return i-L2;
23             }
24         }
25         j = 0;
26         i ++ ;
27     }
28     return -1;
29 }
30 int ans = -1 ;
31 void bfs( ){
32 
33     queue<Node>Q;
34     Q.push ( Node{A,0} );
35     Mp[A] = 1;
36     while ( !Q.empty() ){
37         Node cur = Q.front();
38         Q.pop();
39         if( cur.step >= 11 ) continue;
40         if( cur.S == B ){
41             ans = cur.step;
42             return ;
43         }
44         for(int i=0;i<cnt;i++){
45             string tmp = cur.S;
46             int Len = tmp.length();
47             int L = a[i].length();
48             for( int j=0 ; j < Len ; j++ ) {
49                 int pos = Check(tmp,a[i],j);
50                 if(  pos != -1 && pos != 0 ){
51                     string s1 = tmp.substr(0,pos);
52                     string s2 = b[i];
53                     string s3 = tmp.substr(pos+L);
54                     string t = s1+s2+s3;
55                     //cout<<t<<endl;
56                     if( Mp[t] == 0 ){
57                         Mp[t] = 1;
58                         Q.push(Node{t,cur.step+1});
59                     }
60                 }
61                 if( pos == 0 ){
62                     string s1 = b[i];
63                     string s2 = tmp.substr(pos+L);
64                     string t = s1 + s2 ;
65                     //cout<<t<<endl;
66                     if( Mp[t] == 0 ){
67                         Mp[t] = 1;
68                         Q.push(Node{t,cur.step+1});
69                     }
70                 }
71             }
72         }
73     }
74 }
75 int main() {
76 
77     ios_base :: sync_with_stdio(NULL);
78     cin.tie(NULL);
79     cout.tie(NULL);
80 
81     cin>>A>>B;
82 
83     while( cin>>a[cnt]>>b[cnt] ){
84 
85         if( a[cnt] == "1" && b[cnt]=="1")
86             break;
87         cnt++;
88     }
89     bfs();
90     if(ans==-1){
91         puts("NO ANSWER!");
92     }else{
93         printf("%d\n",ans);
94     }
95     return 0;
96 }
View Code

猜你喜欢

转载自www.cnblogs.com/Osea/p/10890405.html