[AcWing 190] 字串变换
作者:互联网
双向广搜
点击查看代码
#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;
}
- 用两个队列来分别存储从起点开始和从终点开始搜索的路径,每次取出队列长度短的那个进行扩展,在扩展时,取出一层的状态,枚举规则,将符合的状态(下一层)放到队列中去
标签:string,int,db,190,da,qa,字串,AcWing,size 来源: https://www.cnblogs.com/wKingYu/p/16556866.html