题意分析:给一个质数A和一个质数B每次变换可以改变A的各十百千位,问至少经过多少变换才能将A变为B
思路:
利用字符串储存AB,BFS字符串A的每一位的各种情况
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <cmath>
#define x first
#define y second
#define PII pair<int, string>
using namespace std;
const int N = 20000;
int st[N];
int Atoi(string s)
{
int sum = 0;
for(int i = 0; s[i] != '\0'; i ++)
sum = sum * 10 + s[i] - '0';
return sum;
}
bool isprime(int x)
{
if(x < 2) return false;
for(int i = 2; i <= x / i; i ++)
{
if(x % i == 0) return false;
}
return true;
}
int bfs(string a, string b)
{
memset(st, 0, sizeof st);
queue<PII> Q;
st[Atoi(a)] = 1;
Q.push({0, a});
while(!Q.empty())
{
PII now = Q.front();
if(now.y == b) return now.x;
Q.pop();
for(int i = 0; i < 4; i ++)
{
for(int j = 0; j <= 9; j ++)
{
PII p = now;
if(i == 0 && j == 0) continue;
if(j + '0' == p.y[i]) continue;
p.y[i] = j + '0';
if(!isprime(Atoi(p.y))) continue;
if(st[Atoi(p.y)]) continue;
// cout << p.y << endl;
p.x = now.x + 1;
st[Atoi(p.y)] = 1;
if(p.y == b) return p.x; // 不写会TLE...
Q.push(p);
}
}
}
return -1;
}
int main()
{
int t;
cin >> t;
while(t --)
{
string a, b;
cin >> a >> b;
if(bfs(a, b) == -1) cout << "Impossible" << endl;
else
cout << bfs(a, b) << endl;
}
return 0;
}