思路:
- wow
- 第一次独立解出一道略微变形的搜索题。
- dfs:素数筛预处理,对每个数位搜索就可以了。
- 注意:用 pow() 一定要用 (int) 进行类型转换,无论是除法还是取余。因为 pow() 返回值是 double 类型。
代码:
#include <iostream>
#include <cstring>
#include <queue>
#include <cmath>
using namespace std;
const int maxn = 10005 ;
const int submaxn = 100;
bool unprime[maxn];
bool vis[maxn];
int L , R;
int ans;
struct node{
int n;
int step;
friend bool operator > (const node & a , const node & b){
return a.step > b.step;
}
node(int n , int step) : n(n) , step(step) {} ;
};
priority_queue<node , vector<node> , greater<node> > Q;
void isprime(){
memset(unprime,false,sizeof(unprime));
unprime[0] = unprime[1] = true;
for(int i=2;i<=submaxn;i++){
if(!unprime[i]){
for(int j=i*i ; j<maxn ; j+=i)
unprime[j] = true;
}
}
return ;
}
void init(){
ans = 0;
memset(vis , false , sizeof(vis));
while(!Q.empty())
Q.pop();
return ;
}
void qpush(int n , int s){
for(int i=0;i<4;i++){
int left;
int temp;
if(!i){
left = n%1000;
for(int j=1;j<=9;j++){
temp = left + j*1000;
if(vis[temp])
continue;
if(!unprime[temp]){
if(temp == R){
ans = s+1;
return ;
}
Q.push(node(temp , s+1));
vis[temp] = true;
}
}
}
else{
left = n / (int)pow(10,4-i) * pow(10,4-i) + n % (int)pow(10 , 3-i) ;
for(int j=0;j<=9;j++){
temp = left + j * pow(10 , 3-i);
if(vis[temp])
continue;
if(!unprime[temp]){
if(temp == R){
ans = s+1;
return ;
}
Q.push(node(temp , s+1));
vis[temp] = true;
}
}
}
}
return ;
}
void bfs(){
if(L == R)
return ;
Q.push(node(L , 0));
vis[L] = true;
while(!Q.empty()){
node t = Q.top();Q.pop();
qpush(t.n , t.step);
if(ans)
return ;
}
return ;
}
int main(){
isprime();
int T;cin>>T;
while(T--){
init();
cin>>L>>R;
bfs();
if(ans || L == R)
cout<<ans<<endl;
else
cout<<"Impossible"<<endl;
}
return 0;
}