|
- #include<iostream>
- #include<string>
- #include<cstdio>
- #include<queue>
- #include<map>
- using namespace std;
- #define FOR(i,a,b) for(int i=a;i<=b;i++)
- string a,b,x[15],y[15];
- int c=1,ans,ttq;
- struct node{string str;int step;};
- map<string,int>mp;
- string hyf(const string &str,int i,int j)
- {
- string ans1="";
- if(i+x[j].size() > str.size() ) return ans1;
- FOR(k,0,x[j].size()-1)
- if(str[i+k]!=x[j][k])
- return ans1;
- ans1=str.substr(0,i);
- ans1+=y[j];
- ans1+=str.substr(i+x[j].size());
- }
- /*string hyf(const string &str,int i,int j){//借鉴了stdcall大爷的思想
- string ans = "";
- if (i+x[j].length() > str.length())
- return ans;
- for (int k=0; k < x[j].length();k++)
- if (str[i+k] != x[j][k])
- return ans;
- ans = str.substr(0,i);
- ans+=y[j];
- ans+=str.substr(i+x[j].length());
- return ans;
- }*/
- void bfs()
- {
- queue <node> q;
- node tt;
- tt.str=a;
- tt.step=0;
- q.push(tt);
- while(!q.empty())
- {
- node u=q.front();
- q.pop();
- if(mp.count(u.str)==1) continue;
- if(u.str==b) {ans=u.step;break;}
- string temp;
- mp[u.str]=1;
- FOR(j,1,c)
- {
- ///ttq=u.str.size()-x[j].size()-1;ttq=max(ttq,0);
- FOR(i,0,u.str.size()-1)
- {
- ///cout<<u.str.size()<<" "<<x[j].size()<<' '<<ttq<<endl;
- temp=hyf(u.str,i,j);
- if(temp!="")
- {
- ///cout<<temp<<endl;
- node v;
- v.str=temp;
- v.step=u.step+1;
- q.push(v);
- }
- }
- }
- }
- if(ans>10 || ans==0)
- cout << "NO ANSWER!" << endl;
- else
- cout<<ans;
- }
- int main()
- {
- cin>>a>>b;
- while(cin >> x[c] >> y[c]) c++;c--;
- bfs();
- return 0;
- }
复制代码 |
|