蒟蒻调成这样也没过:
#include <iostream>
#include <string>
#include <map>
#include <unordered_map>
#include <queue>
#define s std::string
#define p std::pair<s,int>
s a[7][2];
int n,ans = 0x3f3f3f3f;
std::unordered_map<std::string,int> m1,m2;
size_t check(s x,s y,size_t pre)
{
return x.find(y,pre);
}
s change(s x,int i,int to,size_t pos)
{
s s3 = x;
s3.replace(pos,a[i][to].length(),a[i][(to+1)%2]);
return s3;
}
int main()
{
while(std::cin>>a[n][0]>>a[n][1]) n++;
n-=1;
std::queue<p> q;
q.push({a[0][0],0});
m1[a[0][0]] = 0;
m2[a[0][1]] = 0;
while(!q.empty())
{
p t = q.front();
q.pop();
int cnt = t.second;
s ts = t.first;
if(cnt>=10) continue;
for(int i=1;i<=n;i++)
{
size_t pos = check(ts,a[i][0],0),pre = pos;
while(pos != std::string::npos)
{
p u;
u.first = change(ts,i,0,pos);
u.second = cnt+1;
if(m1[u.first])
{
pos = check(ts,a[i][0],pre+1);
pre = pos;
continue;
}
m1[u.first] = u.second;
q.push(u);
pos = check(ts,a[i][0],pre+1);
pre = pos;
}
}
}
q.push({a[0][1],0});
while(!q.empty())
{
p t = q.front();
q.pop();
int cnt = t.second;
s ts = t.first;
if(m1[ts]) ans = std::min(ans,m1[ts]+m2[ts]);
if(cnt>=10) continue;
for(int i=1;i<=n;i++)
{
size_t pos = check(ts,a[i][1],0),pre = pos;
while(pos != std::string::npos)
{
p u;
u.first = change(ts,i,1,pos);
u.second = cnt+1;
if(m2[u.first])
{
pos = check(ts,a[i][1],pre+1);
pre = pos;
continue;
}
m2[u.first] = u.second;
q.push(u);
pos = check(ts,a[i][1],pre+1);
pre = pos;
}
}
}
if(ans > 10) std::cout << "NO ANSWER!";
else std::cout << ans;
return 0;
}
/*
abab baba
a b
b a
*/