/*********
Author Smile
https://vjudge.csgrandeur.cn/contest/477341#problem/H
学到了
1. bfs 又是最短路径的查找,而且还是动态连续的
2. bfs 中必须对符合条件的进行bfs, 如果有不符合条件的 push 进来,很可能会出错,路径的最短或许会变更短
3. bfs 还是一样的模板,最重要的还是分析过程
*********/
#include <iostream>
#include <queue>
#include <cmath>
#include <cstring>
using namespace std;
const int N = 1e4 + 10;
int T;
int money[N];
int vis[N];
int t[4];
void fenjie(int x)
{
t[0] = x / 1000;
t[1] = x % 1000 / 100;
t[2] = x % 100 / 10;
t[3] = x % 10;
}
int number(int a, int b, int c, int d)
{
return a * 1000 + b * 100 + c * 10 + d;
}
int prime(int x)
{
int temp = sqrt(x);
if (x < 1000 || x > 10000)
return 0;
for (int i = 2; i <= sqrt(x); ++i)
{
if (x % i == 0)
return 0;
}
return 1;
}
int bfs(int x, int y)
{
queue<int> q;
q.push(x);
vis[x] = 1;
if (x == y)
return 0;
while (!q.empty())
{
int v = q.front();
q.pop();
fenjie(v);
// cout << v << ' ' << y << endl;
// cout << t[0] << ' ' << t[1] << ' ' << t[2] << ' ' << t[3] << endl;
for (int i = 0; i <= 3; ++i)
{
int temp = t[i];
for (int j = 0; j <= 9; ++j)
{
if (j == temp)
continue;
t[i] = j;
int vtemp = number(t[0], t[1], t[2], t[3]);
if (!vis[vtemp] && prime(vtemp))
{
vis[vtemp] = 1;
money[vtemp] = money[v] + 1;// bfs 动态记录路径
q.push(vtemp);
}
if (vtemp == y)
return money[vtemp];
}
t[i] = temp;
}
if (v == y)
return money[v];
}
return -1;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> T;
while (T--)
{
int a, b;
cin >> a >> b;
memset(vis, 0, sizeof vis);
memset(money, 0, sizeof money);
int pos = bfs(a, b);
if (pos == -1)
cout << "Impossible" << endl;
else
cout << pos << endl;
}
return 0;
}
07-18
697
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-29
1045
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)