Prime Path POJ - 3126
题目链接:https://vjudge.net/problem/POJ-3126
题意:给你两个四位的素数N,M,每次改变N四位数中的其中一位,如果能经过有限次数的替换变成四位数M,那么求出最少替换次数,否则输出“Impossible”.(N,M必须一直是素数)
思路:bfs。四位数,每一位可以替换为0~9,那么我们可以每次改变N中的一位数,然后放入队列中,当然,在替换数字时难免会出现重复的四位数,这样会造成TLE,那么我们可以创建一个bool数组标记出现过的,我们也需要素数筛999 ~ 10000之间的素数(你想删哪里到哪就哪里,不要纠结),因为是bfs,所以第一次出现的新的四位素数一定是替换次数最少的,那么题目就简单了。
#include <iostream>
#include <cstring>
#include <cmath>
#include <queue>
#include <algorithm>
using namespace std;
#define inf (1LL << 31) - 1
#define rep(i,j,k) for(int i = (j); i <= (k); i++)
#define rep__(i,j,k) for(int i = (j); i < (k); i++)
#define per(i,j,k) for(int i = (j); i >= (k); i--)
#define per__(i,j,k) for(int i = (j); i > (k); i--)
const int N = (int)1e4 + 10;
bool vis[N]; //素数表 0为素数
bool app[N]; //标记是否出现过
int ans;
struct node{
int a[4];
int cost;
node(int* a,int e){
rep(i, 0, 3){
this->a[i] = a[i];
}
this->cost = e;
}
int x(){ //返回四位数的成员函数
int num = 0;
rep(i, 0, 3) num = num * 10 + a[i];
return num;
}
};
void get_Prime(){ //素数打表
rep(i, 2, (int)sqrt(N*1.0)){
if (!vis[i]){
for (int p = i * i; p <= N; p += i) vis[p] = true;
}
}
}
bool work(int x[], int y){ //true为有答案,false为没答案
queue<node> que;
node t (x,0);
app[t.x()] = true;
que.push(t);
if (t.x() == y){
ans = 0;
return true;
}
while (!que.empty()){
node tmp = que.front();
que.pop();
rep(i, 0, 3){ //1~4不同位置
rep(j, 0, 9){ //替换为0~9
if (i == 0 && j == 0) continue; //第一位不能是0
int tt = tmp.a[i]; //暂存该数
tmp.a[i] = j; //改变
//该四位数没有出现过且该数是素数
if (!app[tmp.x()] && !vis[tmp.x()]){
app[tmp.x()] = true; //标记一下
if (tmp.x() == y){ //如果变成了想变成的数了
ans = tmp.cost + 1;
return true;
}
que.push(node{tmp.a,tmp.cost + 1}); //新的四位数放入队列,花费加一
}
tmp.a[i] = tt; //变回原来的四位数
}
}
}
return false;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
get_Prime();//得到素数表
int n;
cin >> n;
int a, b;
while (n--){
memset(app, 0, sizeof(app)); //每次初始化
cin >> a >> b;
int aa[4];
int len = 0;
rep(i, 0, 3){
aa[3-len++] = a % 10;
a /= 10;
} //分割a变为四个数
//node tmp(aa, 0);
//cout << "tmp:::" << tmp.x() << endl;
if (work(aa, b)) cout << ans << endl;
else cout << "Impossible" << endl;
}
return 0;
}