Aizu 1296 Simple BFS

Source: Internet
Author: User

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=" &LT;&LT;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&LT;&LT;BFS () <<endl; } return 0;}


Aizu 1296 Simple BFS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.