给出两个四位的素数,要求对第一个素数进行一系列操作,每次操作只能改变一位数,且改变后必须仍然是素数,求最少的操作步数。
水题。 搜索加素数判定。普通的bfs就能过了,可悲的是我还刚开始还想用启发式搜索,结果算出来的不是最少步数,于是改成bfs过来。。。。
#include <cstdio>
#include <stack>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <functional>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <string>
#include <map>
#include <iomanip>
#include <cmath>
#define LL long long
#define ULL unsigned long long
#define SZ(x) (int)x.size()
#define Lowbit(x) ((x) & (-x))
#define MP(a, b) make_pair(a, b)
#define MS(arr, num) memset(arr, num, sizeof(arr))
#define PB push_back
#define F first
#define S second
#define ROP freopen("input.txt", "r", stdin);
#define MID(a, b) (a + ((b - a) >> 1))
#define LC rt << 1, l, mid
#define RC rt << 1|1, mid + 1, r
#define LRT rt << 1
#define RRT rt << 1|1
#define BitCount(x) __builtin_popcount(x)
#define BitCountll(x) __builtin_popcountll(x)
#define LeftPos(x) 32 - __builtin_clz(x) - 1
#define LeftPosll(x) 64 - __builtin_clzll(x) - 1
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
using namespace std;
const double eps = 1e-8;
const int MAXN = 300 + 10;
const int MOD = 1000007;
const int M=1e5;
const int N=1e7;
typedef pair<int, int> pii;
typedef pair<int, string> pis;
int p[M];
bool vis[N];
int d[M], ans;
struct node
{
int num;
char a[5];
int step;
node(int b):num(b) { step=0; sprintf(a,"%d",num); }
};
void prime()
{
int i,j,t=sqrt(M);
MS(p,true);
p[1]=p[0]=false;
for (i=4;i<M;i+=2) p[i]=false;
for (i=3;i<t;i++){
if (p[i]) {
for (j=i*i;j<M;j+=(i<<1)) p[j]=false;
}
}
}
int getH(char s[])
{
}
bool bfs(int s,int e)
{
int i,j;
MS(vis,false);
MS(d,0);
queue<int> q;
q.push(s);
vis[s]=true;
while(!q.empty())
{
int t=q.front(); q.pop();
if (t==e) { return true; } // find target,end
char c[5],ch;
sprintf(c,"%d",t); //cout<<t<<endl;
for (i=0;i<4;i++) { // 改变第i位数
for (j=0;j<10;j++) { // 从0到9依次搜索
if ( (i==0 || i==3) && j==0) continue;
if (c[i]==j+'0') continue;
ch=c[i]; c[i]=j+'0';
int r;
sscanf(c,"%d",&r);
if (p[r] && !vis[r]) {
d[r]=d[t]+1;
q.push(r);
vis[r]=true;
}
c[i]=ch;
}
}
}
return false;
}
int main()
{
int i,j,t;
cin>>t;
prime();
while(t--)
{
int s,e;
scanf("%d%d",&s,&e);
if (bfs(s,e)) printf("%d\n",d[e]);
else puts("Impossible");
}
}