P1032 String Conversion and p1032 String Conversion
Description
It is known that there are two strings A, B and A set of string conversion rules (up to 6 Rules ):
A1-> B1
A2-> B2
The meaning of the rule is: the sub-string A1 in A $ can be changed to B1, A2 can be changed to B2 ....
For example, A = 'abc' B = 'xyz'
The conversion rules are as follows:
'Abc'-> 'xu ''ud'-> 'y' y '-> 'yz'
At this time, A can undergo A series of transformations to B, and the transformation process is:
'Abcd'-> 'xud '-> 'xy'-> 'xyz'
Three transformations are performed to convert A to B.
Input/Output Format
Input Format:
Enter the keyboard file name. The file format is as follows:
A BA1 B1 \
A2 B2 |-> conversion rules
....../
The maximum length of all strings is 20.
Output Format:
Output to the screen. The format is as follows:
If A can be converted to B within 10 steps (including 10 steps), the minimum number of transformation steps is output; otherwise, the output is "NO ANSWER! "
Input and Output sample
Input example #1:
abcd xyzabc xuud yy yz
Output sample #1:
3
I have done this before,
However, it is the last vertex that is used only when a table is created.
I redo it today.
To realize the truth:
Never over-reliance on STL!
1 #include<iostream> 2 #include<cstdio> 3 #include<queue> 4 #include<cstring> 5 #include<cstdlib> 6 #include<map> 7 using namespace std; 8 string bg,ed; 9 struct guize10 {11 string a,b;12 }gz[1001];13 struct node14 {15 string zfc;16 int step;17 }now,nxt;18 int num=1;19 map<string,bool>mp;20 int tot=0;21 void bfs()22 {23 queue<node>q;24 now.zfc=bg;now.step=0;25 q.push(now);26 while(q.size()!=0)27 {28 node p=q.front();29 //cout<<p.zfc<<"*4654654"<<endl;30 if(p.zfc==ed)31 {32 printf("%d",p.step);33 exit(0);34 }35 if(p.step>10)36 {37 printf("NO ANSWER!");38 exit(0);39 }40 q.pop();41 mp[p.zfc]=1;42 for(int i=1;i<=num-1;i++)43 {44 string tmp=p.zfc;45 //int where=p.zfc.find(gz[i].a);46 for(int j=0;j<p.zfc.length();j++)47 {48 if(p.zfc[j]==gz[i].a[0])49 {50 int flag=0;51 for(int k=0;k<gz[i].a.length();k++)52 {53 tot++;54 if(tot>=4384380)55 {56 printf("NO ANSWER!");57 exit(0);58 }59 if(p.zfc[j+k]!=gz[i].a[k])60 {61 flag=1;break;62 }63 64 65 }66 if(flag==0)67 {68 int where=j;69 nxt.zfc=p.zfc.replace(where,gz[i].a.length(),gz[i].b);70 p.zfc=tmp;71 if(mp[nxt.zfc]==0)72 {73 74 mp[nxt.zfc]=1;75 nxt.step=p.step+1;76 //cout<<p.zfc<<"****"<<nxt.zfc<<"***"<<nxt.step<<endl;77 q.push(nxt);78 }79 }80 }81 }82 }83 }84 }85 int main()86 {87 freopen("string.in","r",stdin);88 freopen("string.out","w",stdout);89 cin>>bg>>ed;90 while(cin>>gz[num].a>>gz[num].b)91 num++;92 //for(int i=1;i<=num-1;i++)93 // cout<<gz[i].a<<"+++"<<gz[i].b<<endl;94 bfs();95 printf("NO ANSWER!");96 return 0;97 }