P1032 字串变换

//P1032 字串变换

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
using namespace std;

int n;
string S,F;
string ori[50],to[50];

int LS,LF;

struct STA
{
    string s;
    int ans;
}NOW,zz;

int cnt;
queue<STA> que;
map<string,bool> ma;
void bfs()
{
    string now;
    bool flag;
    ma[S]=1;
    NOW.s=S,NOW.ans=0;
    que.push(NOW);
    while(!que.empty())
    {
        NOW=que.front(),que.pop();
        now=NOW.s;
//        cout<<"now:   "<<now<<endl;
        if(NOW.ans>=10)
            continue;
        for(int i=0,len=now.length();i<len;++i)
        {
            for(int j=1;j<=n;++j)
            {
//                cout<<"compare:   "<<now[i]<<" "<<ori[j][0]<<endl;
                if(ori[j].length()>len-i+1)
                    continue;
                if(now[i]==ori[j][0])
                {
                    flag=1;
                    for(int k=i,l=0,tl=ori[j].length();k<len&&l<tl;++k,++l)
                    {
                        if(now[k]!=ori[j][l])
                        {
                            flag=0;
                            break;
                        }
                    }
                    if(flag)
                    {
                        ++cnt;
                        string tmp=now;
                        tmp.replace(tmp.begin()+i,tmp.begin()+i+ori[j].length(),to[j]);
                        if(tmp==F)
                        {
                            printf("%d",NOW.ans+1);
                            exit(0);
                        }
//                        if(cnt==15)
//                            exit(0);
                        if(ma[tmp])
                            continue;
//                        cout<<tmp<<endl;
                        ma[tmp]=1;
                        zz.s=tmp,zz.ans=NOW.ans+1;
                        que.push(zz);
                    }
                }
            }
        }
    }
}


int main()
{
    cin>>S>>F;
    if(S==F)
    {
        puts("0");
        return 0;
    }
//    cout<<S<<" "<<F<<endl;
    n=1;
    while(cin>>ori[n]>>to[n])
        ++n;
    --n;
//    for(int i=1;i<=n;++i)
//        cout<<ori[i]<<" "<<to[i]<<endl;
    bfs();
    puts("NO ANSWER!");
    return 0;
}
原文地址:https://www.cnblogs.com/lovewhy/p/9633880.html