Problem Link
#include <iostream>
#include <queue>
using namespace std;
const int N = 10000;
bool prime[N];
int dist[N];
void sieve()
{
for(int i = 2; i < N; i++)
{
prime[i] = true;
}
for(int i = 3; i * i <= N; i += 2)
{
if(prime[i])
{
for(long k = i * i; k < N; k += i)
{
prime[k] = false;
}
}
}
for(int i = 1000; i < N; i += 2)
{
prime[i] = false;
}
}
int convertToNum(int digit[])
{
int num = 0;
for(int i = 0; i <= 3; i++)
{
num = num * 10 + digit[i];
}
return num;
}
void arr(int digit[], int num)
{
int i = 3;
while(num)
{
int rem = num % 10;
digit[i--] = rem;
num = num / 10;
}
}
void bfs(int n, int m, int digit[])
{
queue<int> q;
q.push(n);
while(!q.empty())
{
int num = q.front();
q.pop();
for(int i = 0; i <= 3; i++)
{
arr(digit, num);
for(int j = 0; j <= 9; j++)
{
digit[i] = j;
int n = convertToNum(digit);
if(prime[n] && dist[n] == -1 && n > 1000)
{
dist[n] = dist[num] + 1;
q.push(n);
}
}
}
}
}
int main()
{
int t, n, m;
sieve();
cin >> t;
while(t--)
{
cin >> n >> m;
int digit[4];
for(int i = 0; i < N; i++)
{
dist[i] = -1;
}
dist[n] = 0;
bfs(n, m, digit);
dist[m] == -1 ? cout<<"Impossible"<<endl : cout<<dist[m]<<endl;
}
}
Comments
Post a Comment