字串变换(双向BFS)

在这里插入图片描述

思路:最小步数模型用BFS去写,但是子串变换的可能是k种那么10步,就是的空间k^10会爆内存,那么用双向广搜优化,A,B同时变化,我们在同一层看有没有A,B可以相互到达的点,如果有那么就是A的距离+B的距离+1,没有就加入搜索,直到这一层搜完。保持两队列大小差不多,当A的小了就去搜A反之

//#pragma GCC optimize(2)
#include<bits/stdc++.h>
 
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=1e9+7;
const int N=2e5+5;
const int inf=0x7f7f7f7f;

int gcd(int a,int b)
{
    
    
    return b==0?a:gcd(b,a%b);
}
 
ll lcm(ll a,ll b)
{
    
    
    return a*(b/gcd(a,b));
}
 
template <class T>
void read(T &x)
{
    
    
    char c;
    bool op = 0;
    while(c = getchar(), c < '0' || c > '9')
        if(c == '-')
            op = 1;
    x = c - '0';
    while(c = getchar(), c >= '0' && c <= '9')
        x = x * 10 + c - '0';
    if(op)
        x = -x;
}
template <class T>
void write(T x)
{
    
    
    if(x < 0)
        x = -x, putchar('-');
    if(x >= 10)
         write(x / 10);
    putchar('0' + x % 10);
}
ll qsm(int a,int b,int p)
{
    
    
    ll res=1%p;
    while(b)
    {
    
    
        if(b&1)
            res=res*a%p;
        a=1ll*a*a%p;
        b>>=1;
    }
    return res;
}
string a[10],b[10];
string A,B;
int n;
int chang(unordered_map<string,int>& da,unordered_map<string,int>& db,queue<string>& q,string a[10],string b[10])
{
    
    
    int dis=da[q.front()];
    while(q.size()&&dis==da[q.front()])
    {
    
    
        auto now=q.front();
        q.pop();
        for(int i=0;i<n;i++)
        {
    
    
            for(int j=0;j<now.size();j++)
            {
    
    
                if(now.substr(j,a[i].size())==a[i])
                {
    
    
                    string t=now.substr(0,j)+b[i]+now.substr(j+a[i].size());
                    if(db.count(t)) return da[now]+db[t]+1;
                    if(da.count(t))continue;
                    da[t]=da[now]+1;
                    q.push(t);
                }
            }
        }
    }
    return 11;
}
int bfs()
{
    
    
    unordered_map<string,int> da,db;
    queue<string> qa,qb;
    qa.push(A);
    qb.push(B);
    da[A]=0;
    db[B]=0;
    int step=0;
    while(qa.size()&&qb.size())
    {
    
    
        int res;
        if(qa.size()<qb.size()) res=chang(da,db,qa,a,b);
        else res=chang(db,da,qb,b,a);
        if(res<=10) return res;
        if(++step>10)return -1;

    }
    return -1;
    


}
int main()
{
    
    
    cin>>A>>B;
    while(cin>>a[n]>>b[n]) n++;

    int ans=bfs();
    if(ans==-1) cout<<"NO ANSWER!"<<endl;
    else cout<<ans<<endl;

    
   
      
   return 0;

}


猜你喜欢

转载自blog.csdn.net/qq_43619680/article/details/110524931