解题思路:本题只有一个拓展方式,即按照题意拓展,最后只需要看最后能不能拓展到即可,只需要注意一下拓展过的点不能再次拓展。
C++代码
#include <bits/stdc++.h>
// #define int long long
using namespace std;
int t, n;
string a, b, c;
int work()
{
unordered_map<string, int> dist;
queue<string> q;
string ss;
for (int i = 0; i < n; i ++ )
{
ss += b[i], ss += a[i];
}
q.push(ss);
dist[ss] = 0;
while (q.size())
{
auto t = q.front();
q.pop();
if (t == c) return dist[t];
string temp;
for (int i = 0; i < n; i ++ )
{
temp += t[n + i], temp += t[i];
}
if (!dist.count(temp))
{
q.push(temp);
dist[temp] = dist[t] + 1;
}
}
return -1;
}
signed main()
{
cin >> t;
for (int i = 1; i <= t; i ++ )
{
cin >> n;
cin >> a >> b >> c;
cout << i << " ";
cout << work() << endl;
}
return 0;
}
创作不易,大家可以在AcWing注册账号,参与一下AC之星计划,我的邀请码是MYRGS。对题解有任何疑问可以在评论区下面评论