【BFS】样例过了但是20pts求助
查看原帖
【BFS】样例过了但是20pts求助
481330
sunyizhe还是MC大佬楼主2025/6/22 21:33
//程序算法:双向搜索
#include <bits/stdc++.h>
using namespace std;
const int N=7;

string from[N],to[N];
string a,b;
int n=1,ans=-1;

queue<string> q1,q2;
map<string,int> M1,M2;

void extend(queue<string>& q,map<string,int>& M1,map<string,int>& M2)
{
    if(q.empty())return; //防止因队列为空取front导致RE

    string u=q.front(),str=u;
    q.pop();

    for(int i=1;i<=n;i++)
    {
        int pos=0;
        while(true)
        {
            pos=str.find(from[i],pos);
            if(pos==string::npos)break;
            
            string v=str;
            v.replace(pos,from[i].size(),to[i]);

            if(M1.count(v))
            {
                pos++; //这里必须pos++,否则continue后无法pos++死循环,Line 36同理
                continue;
            }
            else if(M1[u]+1>10)
            {
                pos++;
                continue;
            }
            else M1[v]=M1[u]+1;

            if(M2.count(v))
            {
                ans=M1[v]+M2[v];
                return;
            }

            q.push(v);
            pos++;
        }
    }
}

void bfs()
{
    if(n==0&&a!=b)return;
    if(n==0&&a==b)
    {
        ans=0;
        return;
    }

    M1[a]=0,M2[b]=0;
    q1.push(a),q2.push(b);

    while(!q1.empty() && !q2.empty()) {
        // 优先扩展较小队列
        if(q1.size() <= q2.size()) {
            extend(q1, M1, M2);
        } else {
            extend(q2, M2, M1);
        }
        if(ans<=10&&ans!=-1)return;
    }
}

void fast_read()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
}

int main()
{
    //freopen("input.in","r",stdin);
    //freopen("output.out","w",stdout);
    
    fast_read();
    
    cin>>a>>b;
    while(cin>>from[n]>>to[n])n++;
    
    bfs();

    if(ans<=10)cout<<ans<<endl;
    else cout<<"NO ANSWER!";
    return 0;
}
2025/6/22 21:33
加载中...