很套路的 bfs
数据也挺水(要不就是这个题目存在规律性) 上 ac 代码,欢迎审阅
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<set>
#include<queue>
using namespace std;
const int maxn = 10000 + 10;
const int INF = 1e9 +7;
typedef long long LL;
int a[maxn], vis[maxn];
int n, x, y;
struct mes {
int v;
int cnt;
};
queue<mes> qu;
void prep() { // 打表
memset(a, 0, sizeof a);
a[1] = 1;
for(int i = 2; i < 10000; ++i) {
if(a[i] == 0) {
for(int j = 2*i; j < 10000; j += i)
a[j] = 1;
}
}
}
int bfs(int s) {
if(s == y) return 0;
while(!qu.empty()) qu.pop();
memset(vis, 0, sizeof vis);
vis[s] = 1;
qu.push((mes){s, 0});
while(!qu.empty()) {
mes t = qu.front(); qu.pop();
for(int i = 1; i <= 1000; i *= 10) {
for(int j = 0; j < 10; ++j) {
if(i == 1000 && j == 0) continue;
int d = t.v%i + j*i + t.v/(i*10)*(i*10);
if(d == y) return t.cnt+1;
if(a[d] == 0) { // 是素数
if(vis[d]) continue;
vis[d] = 1;
qu.push((mes){d, t.cnt+1} );
}
}
}
}
return -1;
}
int main() {
prep();
scanf("%d", &n);
while(n--) {
scanf("%d%d", &x, &y);
int ans = bfs(x);
if(ans == -1) cout << "Impossible" << endl;
else cout << ans << endl;
}
return 0;
}
/*
3
1033 8179
1373 8017
1033 1033
*/