题目链接:
传送门
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
struct node {
int num,step;
};
const int N = 10005;
bool isprime[N],used[N];
int prime[N],change[4], cnt,s,e;
//欧拉筛筛选素数
void oulashai() {
for (int i = 2; i <= N; i++) {
if (!isprime[i]) prime[cnt++] = i;
for (int j = 0; j < cnt; j++) {
if (i * prime[j] > N) break;
isprime[i * prime[j]] = true;
if (i % prime[j] == 0) break;
}
}
}
int bfs(int sta) {
if(sta==e)return 0;
queue<node> q;
node start= {sta,0};
q.push(start);
used[sta]=1;
int f=0;
while(!q.empty()) {
node cur=q.front();
q.pop();
//替换个位数
for(int i=1; i<=9; i=i+2) {
int theNum=cur.num/10*10+i;
if(theNum==e) {
f=cur.step+1;
return f;
}
if(used[theNum]==0&&isprime[theNum]==0) {
used[theNum]=1;
node tmp= {theNum,cur.step+1};
q.push(tmp);
}
}
//替换十位数
for(int i=0; i<=9; i++) {
int theNum=cur.num/100*100+i*10+cur.num%10;
if(theNum==e) {
f=cur.step+1;
return f;
}
if(used[theNum]==0&&isprime[theNum]==0) {
used[theNum]=1;
node tmp= {theNum,cur.step+1};
q.push(tmp);
}
}
//替换百位数
for(int i=0; i<=9; i++) {
int theNum=cur.num/1000*1000+i*100+cur.num%100;
if(theNum==e) {
f=cur.step+1;
return f;
}
if(used[theNum]==0&&isprime[theNum]==0) {
used[theNum]=1;
node tmp= {theNum,cur.step+1};
q.push(tmp);
}
}
//替换千位数
for(int i=1; i<=9; i++) {
int theNum=cur.num%1000+i*1000;
if(theNum==e) {
f=cur.step+1;
return f;
}
if(used[theNum]==0&&isprime[theNum]==0) {
used[theNum]=1;
node tmp= {theNum,cur.step+1};
q.push(tmp);
}
}
}
//如果在搜完所有情况后依然没有所要的结果返回-1
return -1;
}
int main() {
oulashai();
int t;
cin>>t;
while(t--) {
memset(used,0,sizeof(used));
cin>>s>>e;
int ans=bfs(s);
cout<<ans<<endl;
}
return 0;
}
这道题的大致思路是首先,先把当前数存入队列中,然后分别对该数的个位,十位,百位,千位进行处理。每次处理后看当前数字是否为质数,是则存入队列中,并标记该数字为已搜索。如果哪次处理后得到了所需的数字则return步骤数,如果最终没有处理出这个数则返回-1。