Description
The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices.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
One line with a positive number: the number of test cases (at most 100). Then for each test case, one line with two numbers separated by a blank. Both numbers are four-digit primes (without leading zeros).Output
One line for each case, either with a number stating the minimal cost or containing the word Impossible.Sample Input
3 1033 8179 1373 8017 1033 1033
Sample Output
6 7 0
#include#include #include using namespace std; #define HUR 100 #define THO 1000 #define TEN 10 const int maxn=10000; bool prime[maxn+5]; int vis[maxn],s,e; void prime_table(){ int i,j; memset(prime,0,sizeof(prime)); for(i=2;i que; que.push(s); while(!que.empty()){ int t=que.front(); que.pop(); int d=t; d%=1000; for(i=1;i<10;i++){ int tt=d+i*THO; //變換千位 if(prime[tt]==0 && vis[tt]==0){ if(tt==e) return vis[t]; que.push(tt);vis[tt]=vis[t]+1; } } d=t%100+(t/1000*1000); for(i=0;i<10;i++){ int tt=d+i*HUR; //變換百位 if(prime[tt]==0 && vis[tt]==0){ if(tt==e) return vis[t]; que.push(tt);vis[tt]=vis[t]+1; } } d=t%10+t/100*100; for(i=0;i<10;i++){ int tt=d+i*TEN; //變換十位 if(prime[tt]==0 && vis[tt]==0){ if(tt==e) return vis[t]; que.push(tt);vis[tt]=vis[t]+1; } } d=t/10*10; for(i=0;i<10;i++){ int tt=d+i; //變換個位 if(prime[tt]==0 && vis[tt]==0){ if(tt==e) return vis[t]; que.push(tt);vis[tt]=vis[t]+1; } } } return 0; } int main() { int T,res; prime_table(); scanf("%d",&T); while(T--){ scanf("%d%d",&s,&e); if(s==e){ printf("0\n"); continue; } res=bfs(); if(res==0) printf("Impossible\n"); else printf("%d\n",res); } return 0; }