#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <queue>
#include <stack>
using namespace std;
#define N 11000
#define INF 0xfffffff
#define PI acos (-1.0)
#define EPS 1e-8
const int dir[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
struct node
{
int x, t;
}qq;
int sa, en, vis[N];
void BFS (int sa, int en);
int isprime (int x);
int main ()
{
int t;
cin >> t;
while (t--)
{
cin >> sa >> en;
BFS (sa, en);
}
return 0;
}
void BFS (int sa, int en)
{
memset (vis, 0, sizeof (vis));
queue <node> que;
qq = (node) {sa, 0};
que.push(qq);
vis[qq.x] = 1;
while (que.size())
{
qq = que.front(); que.pop();
if (qq.x == en)
{
cout << qq.t << endl;
return;
}
char s1[5], s2[5];
int tt = qq.x;
s1[4] = '\0';
for (int i=3; i>=0; i--)
{
s1[i] = tt % 10 + '0';
tt /= 10;
}
for (int i=0; i<4; i++)
{
strcpy (s2, s1);
for (int j=0; j<=9; j++)
{
if ((!i && !j) || s2[i] == j + '0')
continue;
s2[i] = j + '0';
int num = atoi(s2);
if (num & 1 == 0)
continue;
if (isprime(num) && !vis[num])
{
vis[num] = 1;
node q = (node) {num, qq.t+1};
que.push(q);
}
}
}
}
cout << "Impossible" << endl;
}
int isprime (int x)
{
for (int i=2; i*i<=x; i++)
if (x % i == 0)
return 0;
return 1;
}
hdu--1973 Prime Path
最新推荐文章于 2020-05-25 23:04:30 发布