字串变换

 

 

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1001;
struct st
{
    string x;
    int step;
} q[100005];
int cnt=0,step,fron,rear;
string n,m,a[maxn],b[maxn];
map<string,bool>vis;
int bfs()
{
    st now;
    now.x=n;
    now.step=0;
    fron=rear=0;
    q[rear]=now;
    rear++;
    while(fron<rear)
    {
        now=q[fron++];
        if(now.x==m)
        {
            printf("%d\n",now.step);
            return 0;
        }
        if(now.step>10)
        {
            return -1;
        }
        for(int i=0; i<cnt; i++)
        {
            string temp=now.x;
            int pos=temp.find(a[i]);
            while(pos!=-1)
            {
                temp.replace(pos,a[i].length(),b[i]);
                if(vis[temp]==0)
                {
                    vis[temp]=true;
                    q[rear].x=temp;
                    q[rear].step=now.step+1;
                    rear++;
                }
                temp=now.x;
                pos=temp.find(a[i],pos+1);
            }
        }
    }
    return -1;

}
int main()
{
    cin>>n>>m;
    cnt=0;
    while(cin>>a[cnt]>>b[cnt])
        cnt++;
    if(bfs()<0)
    {
        printf("NO ANSWER!\n");
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值