字串变换----双向广搜

8 篇文章 0 订阅

字串变换

题目链接

在这里插入图片描述
在这里插入图片描述
写法一:dfs

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;
const int N = 7;
string a[N],b[N];
int n=0,res=0x3f3f3f3f;
void dfs(string A,string B,int step)
{
    if(step>10||(res!=0x3f3f3f3f&&res<=step))return ;
    if(A==B)
    {
        res=min(res,step);
        return ;
    }
    for(int i=0;i<n;i++)
    {
        if(A.find(a[i])!=string::npos)
        {
            int pos=A.find(a[i]);
            A.replace(pos,a[i].size(),b[i]);
            dfs(A,B,step+1);
            pos=A.find(b[i]);
            A.replace(pos,b[i].size(),a[i]);
        }
    }
}
int main()
{
    string A,B;
    cin>>A>>B;
    while(cin>>a[n]>>b[n])n++;
    dfs(A,B,0);
    if(res<=10)cout<<res<<endl;
    else cout<<"NO ANSWER!"<<endl;
}

写法二:双端队列广搜

#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#include <queue>

using namespace std;
const int N = 6;
string a[N],b[N];
string A,B;
int idx=0;
int extend(queue<string>&q,unordered_map<string,int>&nowd,unordered_map<string,int>&red,string now[],string re[])
{
    string s=q.front();
    q.pop();
    for(int i=0;i<s.size();i++)
    {
        for(int j=0;j<idx;j++)
        {
            if(s.substr(i,now[j].size())==now[j])
            {
                string str=s.substr(0,i)+re[j]+s.substr(i+now[j].size());
                if(nowd.count(str))continue;
                if(red.count(str))return nowd[s]+1+red[str];
                nowd[str]=nowd[s]+1;
                q.push(str);
            }
        }
    }
    return 11;
}
int bfs()
{
    unordered_map<string,int> da,db;
    queue<string> qa,qb;
    qa.push(A);da[A]=0;
    qb.push(B);db[B]=0;
    int t=0;
    while(qa.size()&&qb.size())
    {
        if(qa.size()<qb.size())t=extend(qa,da,db,a,b);
        else t=extend(qb,db,da,b,a);
        if(t<=10)return t;
    }
    return 11;
}
int main()
{
    cin>>A>>B;
    if(A==B)
    {
        cout<<0<<endl;
        return 0;
    }
    while(cin>>a[idx]>>b[idx])idx++;
    int t=bfs();
    if(t>10)cout<<"NO ANSWER!"<<endl;
    else cout<<t<<endl;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_WAWA鱼_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值