洛谷 P1032 字串变换

P1032 字串变换

 

#include<iostream>
#include<string>
#include<map>
using namespace std;
map<string,bool> map1;
string s1,s2;
int n,l=1,r=0;
int deep[500000];
string que[500000];
string sa[7];
string sb[7];
void in(string s,int deep1)
{
    que[++r]=s;
    deep[r]=deep1;
    map1[s]=true;
}

void do1(string s,string rule1,string rule2,int deep1)
{
    string sx;
    int k=s.find(rule1,0),i;
    bool flag;
    while(k!=string::npos)
    {
        flag=false;
        sx=s;
        sx.erase(k,rule1.length());
        sx.insert(k,rule2);
        if(sx==s2)
        {
            cout<<deep1+1;
            exit(0);
        }
        /*for(i=0;i<didnum;i++)
            if(did[i]==sx)
                flag=true;*/  //此处原来是用did记录所有已搜索到的字串,然后每次遍历did数组判断是否重复,后用map优化
        if(map1.count(sx)==0)
        {
            in(sx,deep1+1);
            //cout<<sx<<k<<endl;
        }
        k=s.find(rule1,k+1);
    }
}
void work()
{
    int i;
    while(l<=r)
    {
        if(deep[l]>=10)
        {
            cout<<"NO ANSWER!";
            exit(0);
        }
        for(i=1;i<=n;i++)
        {
            do1(que[l],sa[i],sb[i],deep[l]);
        }
        l++;
    }
}
int main()
{
    int i;
    cin>>s1>>s2;
    while(cin>>sa[n+1]>>sb[n+1])n++;
    in(s1,0);
    work();
    cout<<"NO ANSWER!";
    return 0;
}


 

posted @ 2017-07-13 12:59  hehe_54321  阅读(96)  评论(0编辑  收藏  举报
AmazingCounters.com