题目大意:有一个素数,变化成另一个素数,至少要几步,每一步,只能变化一位数字,必须变化后的数字也是素数。
解题思路:打表将所有素数找出来,用bfs一步一步搜索。与抓牛类似,一个标记数组,即标记,也是记录步数,第一次找到就返回步数的值。抓牛有详细谈过,这里就不说了。
ac代码:
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
int prime[1090], cnt, n, k, m, vis[10005];
int a[4], b[4];
queue <int>qu;
void pri()
{
int judge;
cnt = 0;
for (int i=1001; i<9999; i++){
judge = 1;
for (int j=2; j<=i/2; j++)
if (i % j == 0){
judge = 0;
break;
}
if (judge)
prime[cnt++] = i;
}
}
int bfs()
{
int judge;
memset(vis, -1, sizeof(vis));
while (!qu.empty())
qu.pop();
qu.push(m);
vis[m] = 0;
int temp1, temp2;
while (!qu.empty()){
temp1 = qu.front();
qu.pop();
if (temp1 == k)
return vis[k];
for (int i=0,n=1; i<4; i++,n*=10)
a[i] = temp1/n%10;
for (int i=0; i<cnt; i++){
judge = 0;
for (int j=0,n=1; j<4; j++,n*=10)
b[j] = prime[i]/n%10;
for (int j=0; j<4; j++)
if (a[j] != b[j])
judge++;
if (judge == 1 && vis[prime[i]] == -1){
qu.push(prime[i]);
vis[prime[i]] = vis[temp1] + 1;
}
}
}
}
int main()
{
pri();
cin >> n;
while (n--){
scanf("%d%d", &m, &k);
cout << bfs() << endl;
}
return 0;
}