Title Link: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1296
Test instructions: Gives some substitution patterns, asking what is the minimum number of replacements required to get the original string by replacing the target string.
Idea: Because the data size is very small (n<=10), and each time the replacement will all replace all can be replaced, and there are many places can be replaced, the first to replace the leftmost string, these conditions make the problem of uncertainty greatly reduced, the direct use of BFS search is good.
Through this problem, familiar with the use of string and map is very good.
Code
#include <cstdio> #include <cstdlib> #include <iostream> #include <algorithm> #include < cstring> #include <map> #include <queue> #include <string>using namespace Std;map<string,int > pam;queue<string> que;int n;string s0[20],s1[20];string org,aim;int bfs () {pam.clear (); pam[org]=0; Que.push (org); while (Que.size ()) {string V=que.front (); Que.pop (); if (V.length () >aim.length ()) continue; for (int i=0;i<n;i++) {int l1=s0[i].length (), l2=v.length (); String u= ""; for (int j=0;j<l2;j++) {if (J+l1-1<l2&&v.substr (J,L1) ==s0[i]) {u+=s1[i]; J=j+l1-1; } else u+=v[j]; }//cout<< "org=" <<v<< "t0=" <<s0[i]<< "t1=" <<s1[i]<< "res=" <<U&L t;<endl; if (!pam.count (u) | | pam[u]>pam[v]+1) {Pam[u]=pam[v]+1; Que.push (U); }}} if (!pam.count (AIM)) return-1; else return Pam[aim];} int main () {while (cin>>n,n!=0) {for (int i=0;i<n;i++) cin>>s0[i]>>s1[i]; cin>>org; cin>>aim; COUT<<BFS () <<endl; } return 0;}
Aizu 1296 Simple BFS