背景:ac的比较顺利,看来写完代码之后再扫视一下全代码是个不错的方法。
思路:就是对千位百位十位个位都进行扩展的广度优先搜索。
这里还提供一种bfs思路:把1000到9999的所有素数都放到list里,每次对于一个数,在list找出所有和它只有一个数字不相同的数字加入队列中,直到找到目标数组。
我的代码
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<vector>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define M 9000
#define INF 100000000
#define LL long long int
using namespace std;
bool list[M],vis[M];
int ans,over;
struct place{int x,step;}temp1,temp2;
bool isprime(int x){
if(x%2 == 0) return false;
for(int i=2;i*i <= x;i++) if(x%i == 0) return false;
return true;
}
int chifang(int j){
int ans=1;
for(int i=1;i <= j;i++)
ans*=10;
return ans;
}
void bfs(void){
queue<place> q;
q.push(temp1);
while(!q.empty()){
temp1=q.front();
vis[temp1.x-1000]=true;
q.pop();
if(temp1.x == over){ans=temp1.step;return;}
for(int i=0;i < 10;i++){
for(int j=0;j < 4;j++){
int y;
if(j == 3) y=(temp1.x-temp1.x%1000)/1000;
if(j == 2) y=(temp1.x%1000-temp1.x%100)/100;
if(j == 1) y=(temp1.x%100-temp1.x%10)/10;
if(j == 0) y=temp1.x%10;
temp2.x=temp1.x-y*chifang(j);
if(j == 3 && i != 0 && i != y){
temp2.x=temp2.x+i*chifang(j);
if(!vis[temp2.x-1000] && list[temp2.x-1000]){
temp2.step=temp1.step+1;
q.push(temp2);
}
}
if(j == 2 && i != y){
temp2.x=temp2.x+i*chifang(j);
if(!vis[temp2.x-1000] && list[temp2.x-1000]){
temp2.step=temp1.step+1;
q.push(temp2);
}
}
if(j == 1 && i != y){
temp2.x=temp2.x+i*chifang(j);
if(!vis[temp2.x-1000] && list[temp2.x-1000]){
temp2.step=temp1.step+1;
q.push(temp2);
}
}
if(j == 0 && i != y && y%2 != 0){
temp2.x=temp2.x+i*chifang(j);
if(!vis[temp2.x-1000] && list[temp2.x-1000]){
temp2.step=temp1.step+1;
q.push(temp2);
}
}
}
}
}
}
int main(void){
int t;
scanf("%d",&t);
memset(list,false,sizeof(list));
for(int i=1000;i < 10000;i++) if(isprime(i)) list[i-1000]=1;
while(t--){
memset(vis,false,sizeof(vis));
scanf("%d%d",&temp1.x,&over);
temp1.step=0;
bfs();
printf("%d\n",ans);
}
return 0;
}