Given the 2 four-digit prime number, a, a, a, requires that a change can only be one of the 4 digits of a, and the number of changes will be prime, ask a at least how many times a change can be changed to B.
Note that the thousand number of a cannot change to 0
First hit the prime table, then the BFS number a can.
1#include <cstdio>2#include <cstring>3#include <queue>4 5 using namespacestd;6 7 Const intmaxn=10010;8 Const intinf=0x3f3f3f3f;9 Ten BOOLPRIME[MAXN]; One BOOLVIS[MAXN]; A - voidinit_prime () - { thememset (Prime,true,sizeofprime); -prime[1]=false; - for(intI=2; i<maxn;i++) - { + if(Prime[i]) - { + for(intj=i*2; j<maxn;j+=i) Aprime[j]=false; at } - } - return ; - } - structNode - { in intnum,cnt; - }; to +InlineintPowintXinty) - { the intret=1; * for(intI=1; i<=y;i++) $ret*=x;Panax Notoginseng returnret; - } the + intBFsintAintb) A { the if(a==b) + return 0; -memset (Vis,false,sizeofvis); $ Node str; $str.num=A; -Str.cnt=0; -Queue<node>que; the while(!que.empty ()) - Que.pop ();Wuyi Que.push (str); thevis[str.num]=true; - while(!que.empty ()) Wu { -Node u=Que.front (); About Que.pop (); $ if(u.num==b) - returnu.cnt; - for(intI=1; i<=4; i++) - { A for(intj=0;j<Ten; j + +) + { the //position I is changed to J - if(i==4&&j==0) $ Continue; the intX= (U.num%pow (Ten, i))/pow (Ten, I-1); the if(x==j) the Continue; the Node tmp; -Tmp.num=u.num-x*pow (Ten, I-1) +j*pow (Ten, I-1); in if(!Prime[tmp.num]) the Continue; the if(Vis[tmp.num]) About Continue; thetmp.cnt=u.cnt+1; the Que.push (TMP); thevis[tmp.num]=true; + } - } the }Bayi } the the intMain () - { - init_prime (); the inttest; thescanf"%d",&test); the while(test--) the { - intb; thescanf"%d%d",&a,&b); the theprintf"%d\n", BFS (A, b));94 } the return 0; the}
View Code
POJ 3126 Prime Path BFS Simple