Title Link: http://poj.org/problem?id=3126
Test instructions: to two four-digit n,m, the number of steps required to change N to M requires that only one digit of n be changed at a time, that is, the changed number is only one difference from the number before the change, and the number after each change is prime.
Analysis: Filter prime +BFS, enumerate each digit to modify, after the change or the prime number of Enter the queue, cycle out of the team, and finally change one step, two steps, three steps ... The number of primes is scattered, like a tree, and the number of steps to be returned is the same as when you want to change the target.
#include <cstdio>#include<cstring>#include<cmath>#include<iostream>#include<algorithm>#include<queue>#include<cstdlib>#include<stack>#include<vector>#include<Set>#include<map>#defineLL Long Long#defineMoD 1000000007#defineINF 0x3f3f3f3f#defineN 100010using namespacestd;unsignedLong LongAns,n,ok;intprime[10010];intvis[10010],step[10010];voidinit () { for(intI= +;i<10000; i++) { for(intj=2; j*j<=i;j++) { intflag=0; if(i%j==0) {Prime[i]=0; flag=1; Break; } if(!flag) prime[i]=1; } }}intBFsintXxintyy) { inta[Ten]; memset (Vis,0,sizeof(VIS)); memset (step,0,sizeof(step)); Queue<int>que; Que.push (XX); VIS[XX]=1; while(!Que.empty ()) { intx=Que.front (); Que.pop (); if(X==YY)returnStep[x]; a[0]=x%Ten; a[1]=x/Ten%Ten; a[2]=x/ -%Ten; a[3]=x/ +; for(intI=0;i<4; i++) { intnum=A[i]; for(intj=0;j<Ten; j + +) if(j!=num) {A[i]=J; intcnt=a[0]+Ten*a[1]+ -*a[2]+ +*a[3]; if(!vis[cnt]&&prime[cnt]) {step[cnt]=step[x]+1; vis[cnt]=1; Que.push (CNT); }} A[i]=num; } } return-1;}intMain () {intT,a,b,res; Init (); scanf ("%d",&T); while(t--) {scanf ("%d%d",&a,&b); Res=BFS (A, b); if(res==-1) printf ("impossible\n"); Elseprintf"%d\n", RES); }}View Code
poj3126 (BFS)