1 条题解

  • 0
    @ 2023-4-27 21:37:16
    #include <bits/stdc++.h>
    using namespace std;
     
    const int N = 6;
    int n;
    string A, B;
    string a[N], b[N];
     
    int extend(queue<string> &q, unordered_map<string,int>&da, unordered_map<string,int>&db, string a[], string b[])
    {
        int d = da[q.front()];//标记队头元素的距离,因为我们只枚举距离相等的这一层
        while(q.size() && da[q.front()] == d)
        {
            auto t = q.front();
            q.pop();
            
            for(int i = 0; i < n; i ++ )
                for(int j = 0; j < t.size(); j ++ )
                    if(t.substr(j, a[i].size()) == a[i])//如果说是满足规则的
                    {
                        string r = t.substr(0, j) + b[i] + t.substr(j + a[i].size());
                        if(db.count(r)) return da[t] + db[r] + 1;//如果说在b中已经找到了这个r,那么就说明连通了,距离就是这个
                        if(da.count(r)) continue;//如果说a中已经有了,就不用重复搜索了
                        da[r] = da[t] + 1;
                        q.push(r);//没有则放进去
                    }
        }
        return 11;
    }
     
    int bfs()
    {
        if(A == B)  return 0;
        queue<string> qa, qb;//两个队列同时搜索
        unordered_map<string, int> da, db;//一个记录到A的距离,一个记录到B的距离
        qa.push(A), qb.push(B);
        da[A] = db[B] = 0;
        
        int step = 0;
        while(qa.size() && qb.size())//如果一方没有了 说明不连通
        {
            int t;
            if(qa.size() <= qb.size())  t = extend(qa, da, db, a, b);//一个是从前往后,a的距离,b的距离,把a变成b
            else    t = extend(qb, db, da, b, a);//从后往前,b的距离,a的距离,把b变成a,规则倒着用
            
            if (t <= 10) return t;
            if ( ++ step == 10) return -1;//记录一下步数,如果搜索了十步还是没有找到解
            
        }
        return -1;
    }
     
    int main()
    {
        cin >> A >> B;
        while(cin >> a[n] >> b[n]) n ++;
        
        int t = bfs();
        if(t == -1) puts("NO ANSWER!");
        else
            cout << t << endl;
        return 0;
    }
    
    • 1

    信息

    ID
    101
    时间
    1000ms
    内存
    128MiB
    难度
    9
    标签
    递交数
    331
    已通过
    36
    上传者