Test instructions: A 4-bit prime number changes one digit at a time, and the middle process also takes the prime number, asking to be the smallest step of the other.
After a linear sieve, the BFS will be fine again. I write the two-way, actually not necessary.
#include <cstdio>#include<iostream>#include<string>#include<cstring>#include<queue>#include<vector>#include<stack>#include<vector>#include<map>#include<Set>#include<algorithm>#include<cmath>//#include <bits/stdc++.h>using namespaceStd;typedefLong Longll;Const intMAXN =1e5;BOOLISNOT[MAXN];voidSeive (intn = maxn-1){ intm = sqrt (n+0.5); for(inti =2; I <= m; i++){ if(!Isnot[i]) for(intj = i*i; J <= N; J + =i) {Isnot[j]=true; }} isnot[0] = isnot[1] =true;}intD[MAXN];intvis[2][MAXN],CLK;#definePB push_back#definePS pushConst intWei[] = {1,Ten, -, +};voidDOUBLEBFS (intSintt) { if(s = = t) {Puts ("0");return; } Queue<int> q[3]; Queue<int> *q1 = Q, *q2 = q+1, *NXT = q+2; int*v1 = *vis, *v2 = vis[1]; Q1->ps (s); Q2->PS (t); V1[s]= ++CLK; V2[T] =CLK; D[s]=0; D[T] =0; while(Q1->size () && q2->size ()) { if(Q1->size () >q2->size ()) {swap (Q1,Q2); swap (V1,V2); } while(q1->size ()) { intU = Q1->front (); Q1->pop (); intdig[4]; for(inti =0; I <4; i++) {Dig[i]= u/wei[i]%Ten; } for(inti =0; I <4; i++){ intt = u-dig[i]*Wei[i]; for(intj = i = =3; J <Ten; J + +){ if(J! =Dig[i]) { intv = t+j*Wei[i]; if(!isnot[v] && v1[v]! =CLK) { if(V2[v] = =CLK) {printf ("%d\n", d[v]+d[u]+1); return; } D[v]= d[u]+1; NXT-PS (v); V1[V]=CLK; }}}}} swap (Q1,NXT); } puts ("Impossible");}//#define LOCALintMain () {#ifdef LOCAL freopen ("In.txt","R", stdin);#endifseive (); intT scanf"%d",&T); while(t--){ intb; scanf"%d%d",&a,&b); Doublebfs (A, b); } return 0;}
POJ 3126 Prime Path