Prime Path
原题链接
题解
题目的意思是给你两个素数a,b,问你每次只能改变一个数字a-->b的素数路径最小是多少。先利用素数筛把素数10000以内的素数选出来,方便计算。然后直接利用BFS枚举所有的情况。
代码如下
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 10010;
int judge[N] = {1, 1};
int prime[N];
int numprime = 0;
int st[N];
void init(){
for(int i = 2; i < N; ++ i){
if(judge[i] == 0) prime[numprime ++] = i;
for(int j = 0; j < numprime && i * prime[j] < N; ++ j){
judge[i * prime[j]] = 1;
if(i % prime[j] == 0) break;
}
}
}
int changed(int num, int op, int temp){
int ans = 0;
if(op == 0) ans = num % 1000 + temp * 1000;
else if(op == 1) ans = num / 1000 * 1000 + num % 100 + temp * 100;
else if(op == 2) ans = num / 100 * 100 + temp * 10 + num % 10;
else ans = num / 10 * 10 + temp;
return ans;
}
int main(){
init();
int T; cin >> T;
while(T --){
memset(st, -1, sizeof st);
int n, m; cin >> n >> m;
queue<int> q; q.push(n);
st[n] = 0;
int res = -1;
while(q.size()){
int t = q.front(); q.pop();
if(t == m) {res = st[t]; break;}
for(int i = 0; i < 4; ++ i){
for(int j = 0; j <= 9; ++ j){
if(i == 0 && j == 0) continue;
int temp = changed(t, i, j);
if(st[temp] == -1 && judge[temp] == 0) q.push(temp), st[temp] = st[t] + 1;
}
}
}
if(res == -1) cout << "Impossible" << '\n';
else cout << res << endl;
}
return 0;
}
如有错误,欢迎指正!