Description
The ministers of the Cabinet were quite upset by the message from the chief of Security stating, they would all has T o Change the Four-digit-numbers on their offices.
-it is a matter of security to change such things every now and then, to keep the enemy in the dark.
-but look, I had chosen my number 1033 for good reasons. I am The Prime minister, you know!
-I know, so therefore your new number 8179 is also a prime. You'll just has to paste four new digits over the four old ones on your office door.
-no, it ' s not so simple. Suppose that I change the first digit to an 8 and then the number would read 8033 which is not a prime!
-I see, being the Prime Minister you cannot stand have a non-prime number on your door even for a few seconds.
-correct! So I must invent a scheme for going from 1033 to 8179 by a path of the prime numbers where only one digit are changed from one Prime to the next prime.
Now, the Minister of Finance, who had been eavesdropping, intervened.
-no unnecessary expenditure, please! I happen to know then the price of a digit is one pound.
-HMM, in this case I need a computer program to minimize the cost. You don ' t know some very cheap software gurus?
-in fact, I do. You see, there are this programming contest going on ... Help the Prime minister to find the cheapest prime path between any and given Four-digit primes! The first digit must be nonzero, of course. Here's a solution in the case above.
1033
1733
3733
3739
3779
8779
8179
The cost of this solution is 6 pounds. Note that the digit 1 which got pasted over step 2 can is reused in the last Step–a new 1 must is purchased. The topic is that every time a number, and the requirement is a prime number, and then ask the minimum change several times into the target, the typical BFS, first filter out all the primes immediately after the search is good. The code is as follows:
#include <iostream>#include<cstring>#include<queue>using namespacestd;BOOLrem[10005];intrans[10005];voidGetprime () { for(intI=2;i<10000;++i)if(rem[i]==0) for(intj=i*2;j<10000; j+=i) rem[j]=1; }intBFsintSintE) {memset (rans,-1,sizeof(rans)); Queue<int>que; intT; inttemp; Que.push (S); Rans[s]=0; while(!Que.empty ()) {T=Que.front (); Que.pop (); if(t==E)returnRans[e]; for(intI=1; i<=9;++i) {temp=t% ++i* +; if(rans[temp]==-1&&rem[temp]==0) {Rans[temp]=rans[t]+1; Que.push (temp); } } for(intI=0; i<=9;++i) {temp=t% -+ -*i+ (t/ +)* +; if(rans[temp]==-1&&rem[temp]==0) {Rans[temp]=rans[t]+1; Que.push (temp); } } for(intI=0; i<=9;++i) {temp=t%Ten+Ten*i+ (t/ -)* -; if(rans[temp]==-1&&rem[temp]==0) {Rans[temp]=rans[t]+1; Que.push (temp); } } for(intI=0; i<=9;++i) {temp= (t/Ten)*Ten+i; if(rans[temp]==-1&&rem[temp]==0) {Rans[temp]=rans[t]+1; Que.push (temp); } } } return-1;}intMain () {Ios::sync_with_stdio (false); Getprime (); intT; intb; intans; CIN>>u; while(t--) {cin>>a>>b; Ans=BFS (A, b); if(ans==-1) cout<<"impossible\n"; Elsecout<<ans<<Endl; } return 0;}
View Code
Simple POJ 3126 Prime Path,bfs.