题意:给你两个素数n,m,问最少多少步可以从n变为m?(1000<= n,m < 10000)每一步可以将n中的一位数字改变其他位不变,并且改变之后的数为素数。
思路:显然,n为起始状态,m为终止状态,用bfs找最短路。
#include <cstdio>
#include <algorithm>
#include <iostream>
#include<vector>
#include<cmath>
#include<set>
#include<cstring>
#include<sstream>
#include<queue>
#include<map>
using namespace std;
typedef long long ll;
const int maxn = 1299709 + 10;
const int maxt = 100200;
const int inf = 0x3f3f3f3f;
const ll INF = 0x7f7f7f7f7f7f7f7f;
const int mod = 1e9 + 7;
const double pi = acos(-1.0);
const double eps = 1e-8;
int n, m, k, t;
int vis[maxn];
int p[maxt];
int d[maxn];
void init(){
for(int i = 2; i <= 10000; ++i){
if(!vis[i]){
for(int j = i + i; j <= 10000; j += i)
vis[j] = 1;
}
}
t = 0;
for(int i = 1000; i < 10000; ++i)
if(!vis[i]) p[t++] = i;
}
int ans[maxn];
void bfs(){
queue<int> q;
q.push(n);
memset(d, 0, sizeof d);
d[n] = 1;
ans[n] = 0;
while(!q.empty()){
int x = q.front(); q.pop();
if(x == m) {printf("%d\n", ans[m]); break;}
int t1 = x % 10;
int t2 = (x / 10) % 10;
int t3 = (x / 100) % 10;
int t4 = (x / 1000) % 10;
int x1 = x - t1, x2 = x - t2 * 10, x3 = x - t3 * 100, x4 = x - t4 * 1000;
for(int i = 0; i < 10; ++i){
if(!vis[x1 + i] && i != t1 && !d[x1 + i]) {q.push(x1 + i); ans[x1 + i] = ans[x] + 1;d[x1 + i] = 1;}
if(!vis[x2 + i * 10] && i != t2 && !d[x2 + i * 10]) {q.push(x2 + i * 10); ans[x2 + i * 10] = ans[x] + 1;d[x2 + i * 10] = 1;}
if(!vis[x3 + i * 100] && i != t3 && !d[x3 + i * 100]) {q.push(x3 + i * 100); ans[x3 + i * 100] = ans[x] + 1;d[x3 + i * 100] = 1;}
if(!vis[x4 + i * 1000] && i != t4 && i > 0 && !d[x4 + i * 1000]) {q.push(x4 + i * 1000); ans[x4 + i * 1000] = ans[x] + 1;d[x4 + i * 1000] = 1;}
}
}
}
int main(){
init();
int T;
scanf("%d", &T);
while(T--){
scanf("%d%d", &n, &m);
bfs();
}
}