Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7574 | Accepted: 4302 |
Description
1033The cost of this solution is 6 pounds. Note that the digit 1 which got pasted over in step 2 can not be reused in the last step – a new 1 must be purchased.
1733
3733
3739
3779
8779
8179
Input
Output
Sample Input
3 1033 8179 1373 8017 1033 1033
Sample Output
6 7 0
Source
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <cmath>
using namespace std;
struct node
{
int val,dis;
};
bool is(int &n)
{
if(n%2==0) return false;
int i,m=sqrt(double(n));
for(i=3;i<=m;i++)
if(n%i==0)
return false;
return true;
}
int n,m;
int Cos(int val)
{
bool h[10000]={0};
int i,k,t;
node a,b;a.dis=0;a.val=val;
queue<node >Q;
h[val]=1;
Q.push(a);
while(!Q.empty())
{
a=Q.front();Q.pop();
k=a.val/10*10;
for(i=1;i<=9;i+=2)
{
t=k+i;
if(is(t)&&!h[t])
{
if(t==m)
return a.dis+1;
h[t]=1;
b.val=t;
b.dis=a.dis+1;
Q.push(b);
}
}
t=a.val%10;
k=a.val/100*100+t;
for(i=0;i<=9;i++)
{
t=k+i*10;
if(is(t)&&!h[t])
{
if(t==m)
return a.dis+1;
h[t]=1;
b.val=t;
b.dis=a.dis+1;
Q.push(b);
}
}
t=a.val%100;
k=a.val/1000*1000+t;
for(i=0;i<=9;i++)
{
t=k+i*100;
if(is(t)&&!h[t])
{
if(t==m)
return a.dis+1;
h[t]=1;
b.val=t;
b.dis=a.dis+1;
Q.push(b);
}
}
k=a.val%1000;
for(i=1;i<=9;i++)
{
t=k+i*1000;
if(is(t)&&!h[t])
{
if(t==m)
return a.dis+1;
h[t]=1;
b.val=t;
b.dis=a.dis+1;
Q.push(b);
}
}
}
return -1;
}
int main()
{
int t;
scanf("%d",&t);
int cost;
while(t--)
{
scanf("%d%d",&n,&m);
if(n==m) {printf("0\n");continue;}
cost=Cos(n);
if(cost==-1)
printf("Impossible\n");
else
printf("%d\n",cost);
}
return 0;
}