Topic Connection: http://poj.org/problem?id=3126
Test instructions: Given two prime numbers, find the shortest prime number path between the two.
This problem with a single bfs is enough, but, or practice the double BFS.
Code:
#include <iostream> #include <sstream> #include <cstring> #include <cstdio> #include <cmath
> #include <algorithm> #include <queue> #include <set> #include <map> #include <vector>
#include <string> #define LL __int64 #define INF 0xFFFFFFFF using namespace std;
struct node{int x,step;};
int prime[10000],vis[2][10000],m,n;
void Init () {memset (prime,0,sizeof (prime));p rime[0]=prime[1]=1;
for (int i=2;i< (int) sqrt (100000.5), i++) if (!prime[i]) for (int j=i*i;j<10000;j+=i) prime[j]=1;
} void BFs () {memset (vis,0,sizeof (VIS));
Queue<node> q[2]; Q[0].push (node) {m,0});
Q[1].push (node) {n,0});
Vis[0][m]=1;vis[1][n]=1;
int deep=0; while (! Q[0].empty () | | !
Q[1].empty ()) {int i=0;
while (I<2) {node Tp=q[i].front ();
if (tp.step!=deep) {i++;continue;}
Q[i].pop (); int t[4];//gets each digit t[0]=tp.x%10;
t[1]= (TP.X/10)%10; t[2]= (tp.x/100)%10;
T[3]= (tp.x/1000);
for (int j=0;j<4;j++) {//change position int y=0;
for (int k=3;k>=0;k--)//place the position that needs to be changed to 0 if (k!=j) y=y*10+t[k];
else y=y*10;
for (int k=0;k<10;k++) {//enum change the value of the position int ty=y+k* (int) pow (10,j);
if (Vis[1-i][ty]) {cout<< (deep*2+i+1) <<endl;return;}
if (Vis[i][ty] | | prime[ty] | | ty<1000) continue;
Q[i].push (node) {ty,deep+1});
Vis[i][ty]=1;
}}} deep++;
}} int main () {init ();
int t;cin>>t;
while (t--) {scanf ("%d%d", &m,&n);
if (m==n) {cout<<0<<endl;continue;}
BFS ();
} return 0;
}