ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[AcWing 190] 字串变换

2022-08-06 12:43:58  阅读:12  来源: 互联网

标签:string int db 190 da qa 字串 AcWing size


image
image

双向广搜


点击查看代码
#include<bits/stdc++.h>

using namespace std;

typedef long long LL;

const int N = 10 + 10;

int n;
string A, B;
string a[N], b[N];
queue<string> qa, qb;
map<string,int> da, db;

int extend(queue<string> &q, map<string,int> &da, 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 < t.size(); i ++)
            for (int j = 0; j < n; j ++)
                if (t.substr(i, a[j].size()) == a[j]) {
                    string r = t.substr(0, i) + b[j] + t.substr(i + a[j].size());
                    if (db.count(r))
                        return da[t] + 1 + db[r];
                    if (da.count(r))
                        continue;
                    da[r] = da[t] + 1;
                    q.push(r);
                }
    }
    return 11;
}

int bfs()
{
    if (A == B)
        return 0;
    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);
        else
            t = extend(qb, db, da, b, a);
        if (t <= 10)
            return t;
        if (++ step == 10)
            return -1;
    }
    return -1;
}

void solve()
{
    cin >> A >> B;
    while (cin >> a[n] >> b[n])
        n ++;
    int t = bfs();
    if (t == -1)
        cout << "NO ANSWER!" << endl;
    else
        cout << t << endl;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    solve();

    return 0;
}

  1. 用两个队列来分别存储从起点开始和从终点开始搜索的路径,每次取出队列长度短的那个进行扩展,在扩展时,取出一层的状态,枚举规则,将符合的状态(下一层)放到队列中去

标签:string,int,db,190,da,qa,字串,AcWing,size
来源: https://www.cnblogs.com/wKingYu/p/16556866.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有