rt,爆搜可过。
Code:
#include <bits/stdc++.h>
using namespace std;
int s, T;
int ma[10000010];
int p[10] = {0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000};
int bfs(int s) {
queue<pair<int, int>> q;
q.push({s, 6});
ma[s * 10 + 6] = 1;
while (q.size()) {
auto t = q.front();
int tmp = q.front().first * 10 + t.second;
// cout << tmp << endl;
q.pop();
if (t.first == T) {
return ma[t.first * 10 + t.second] - 1;
}
// cout << "OvO\n";
if (t.second != 1) {
if (!ma[t.first * 10 + t.second - 1]) {
ma[t.first * 10 + t.second - 1] = ma[tmp] + 1;
q.push({t.first, t.second - 1});
}
}
// cout << "OvO\n";
if (t.second != 6) {
if (!ma[t.first * 10 + t.second + 1]) {
ma[t.first * 10 + t.second + 1] = ma[tmp] + 1;
q.push({t.first, t.second + 1});
}
}
// cout << "OvO\n";
if ((t.first % p[t.second + 1]) / p[t.second] != 0) {
t.first -= p[t.second];
if (!ma[t.first * 10 + t.second]) {
ma[t.first * 10 + t.second] = ma[tmp] + 1;
q.push({t.first, t.second});
}
t.first += p[t.second];
}
// cout << "OvO\n";
if ((t.first % p[t.second + 1]) / p[t.second] != 9) {
t.first += p[t.second];
if (!ma[t.first * 10 + t.second]) {
ma[t.first * 10 + t.second] = ma[tmp] + 1;
q.push({t.first, t.second});
}
t.first -= p[t.second];
}
// cout << "OvO\n";
if (t.second != 6) {
int t1 = t.first / p[6], t2 = (t.first % p[t.second + 1]) / p[t.second];
t.first -= t1 * p[6] - t2 * p[6];
t.first -= t2 * p[t.second] - t1 * p[t.second];
if (!ma[t.first * 10 + t.second]) {
ma[t.first * 10 + t.second] = ma[tmp] + 1;
q.push({t.first, t.second});
}
t.first += t1 * p[6] - t2 * p[6];
t.first += t2 * p[t.second] - t1 * p[t.second];
}
// cout << "OvO\n";
if (t.second != 1) {
int t1 = (t.first % 10), t2 = (t.first % p[t.second + 1]) / p[t.second];
t.first -= t1 * p[1] - t2 * p[1];
t.first -= t2 * p[t.second] - t1 * p[t.second];
if (!ma[t.first * 10 + t.second]) {
ma[t.first * 10 + t.second] = ma[tmp] + 1;
q.push({t.first, t.second});
}
t.first += t1 * p[1] - t2 * p[1];
t.first += t2 * p[t.second] - t1 * p[t.second];
}
// cout << "OvO\n";
}
return -1;
}
int main() {
scanf("%d%d", &s, &T);
printf("%d\n", bfs(s));
return 0;
}