实际上通过开始结尾已知的情况下,我可以对一个树采用同时正向负向搜索,很重要的一个
概念是每次控制同一层
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define PII pair<int, int>
#define PLL pair<ll, ll>
const int N = 1e6 + 10;
const int M = 2 * N;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const double PI = acos(-1.0);
const double eps = 1e-8;
string a[N],b[N];
string A,B;
int n;
unordered_map<string,int>da,db;
queue<string>qa,qb;
int exent(queue<string>&qa,unordered_map<string,int>&da,unordered_map<string,int>&db,string a[],string b[])
{
int d = da[qa.front()];
while(qa.size() && da[qa.front()] == d)//至关重要的同一层处理
{
auto t = qa.front();
qa.pop();
for(int i = 0; i < n; i ++)//遍历所有转化方式
{
for(int j = 0; j < t.size(); j ++)//字符串上限20长度更优
{
string sa = a[i];
string sb = b[i];
int m = sa.size();
if(t.substr(j,m) == sa)
{
string res = t.substr(0,j) + sb + t.substr(j + m);
if(da.count(res)) continue;
if(db.count(res)) return da[res] + db[res] + 1;
da[res] = da[t] + 1;
qa.push(res);
}
}
}
}
return -1;
}
int double_bfs()
{
int temp = 0;
if(A == B) return 0;
qa.push(A),da[A] = 0;
qb.push(B),db[B] = 0;
while(qa.size() && qb.size())
{
int k;
if(qa.size() <= qb.size()) k = exent(qa,da,db,a,b);
else k = exent(qb,db,da,b,a);
if(k == -1) ++ temp;
else return ++ temp;
if(temp == 10) return -1;
}
return -1;
}
void solve()
{
cin >> A >> B;
while(cin >> a[n] >> b[n]) n ++;
int t = double_bfs();
if(t == -1) puts("NO ANSWER!");
else cout << t << endl;
}
int main()
{
solve();
system("pause");
return 0;
}