您的位置:首页 > 其它

POJ 3126 Prime Path(搜索)

2016-01-17 22:11 375 查看
AC代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <queue>
using namespace std;

struct node{
int pos,t;
bool operator < (const node &a)const{
return t > a.t;
}
};
int prime[10005];
int vis[10005];

void is_prime(){
memset(prime,0,sizeof(prime));
for(int i = 1000; i < 10000; i++){
int tmp = sqrt(i*1.0),flag = 1;
for(int j = 2; j <= tmp; j++){
if(i%j == 0){
flag = 0;
break;
}
}
if(flag)
prime[i] = 1;
}
}

int bfs(int a,int b){
memset(vis,0,sizeof(vis));
node cur;
int num[4];
cur.pos = a;cur.t = 0;
vis[a] = 1;
priority_queue<node> q;
q.push(cur);
while(!q.empty()){
cur = q.top();
q.pop();
if(cur.pos == b){
return cur.t;
}
int tmppos = cur.pos;
for(int i = 3; i >= 0; i--,tmppos/=10){
num[i] = tmppos%10;
}
for(int i = 0; i < 4; i++){
int tmp = num[i];
for(int j = 0; j < 10; j++){
if(num[i] != j){
num[i] = j;
int pos = num[0]*1000+num[1]*100+num[2]*10+num[3];
if(prime[pos] && !vis[pos]){
vis[pos] = 1;
q.push(node{pos,cur.t+1});
}
}
num[i] = tmp;
}
}
}
return -1;
}

int main(){
is_prime();
int T;
scanf("%d",&T);
while(T--){
int a,b;
scanf("%d%d",&a,&b);
int ans = bfs(a,b);
if(ans < 0)
printf("Impossible\n");
else
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: