题解
BFS按照题意进行搜索,尝试改变每一位数字,改变为0~9的数值,出现的数字不在入队,注意最高位数字不能为0。
AC代码
#include <stdio.h>
#include <iostream>
#include <queue>
#define fst first
#define sed second
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const int N = 1e4;
bool pri[N], vis[N];
int BFS(int a, int b)
{
memset(vis, 0, sizeof(vis));
queue<pair<int, int>> q;
q.push(make_pair(a, 0 ));
int arr[10];
while (!q.empty())
{
int t = q.front().fst, p = q.front().sed + 1;
q.pop();
for (int k = 0; k < 4; ++k)
arr[k] = t % 10, t /= 10;
for (int i = 0; i < 4; ++i) //位
for (int j = i == 3; j < 10; ++j) //数
{
int c = 0;
for (int k = 3; k >= 0; --k)
{
c *= 10;
c += k == i ? j : arr[k];
}
if (c == b)
return p;
if (pri[c] || vis[c])
continue;
vis[c] = 1;
q.push(make_pair(c, p));
}
}
return -1;
}
int main()
{
#ifdef LOCAL
freopen("C:/input.txt", "r", stdin);
#endif
for (int i = 2; i < N; ++i)
if (!pri[i])
for (int j = i + i; j < N; j += i)
pri[j] = 1;
int T;
cin >> T;
while (T--)
{
int a, b;
cin >> a >> b;
if (a == b)
{
cout << 0 << endl;
continue;
}
int res = BFS(a, b);
if (~res)
cout << res << endl;
else
cout << "Impossible" << endl;
}
return 0;
}