题目:http://poj.org/problem?id=3126
题目大意:给你两个素数a、b,每次改变一个数位,这得到的数字也要是素数,问你a变成b最少需要几步?题目保证有解。
解题思路:简单搜索题。打个素数表,然后BFS即可。
代码如下:
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
int is_prime[11111],pow[11];
bool vis[11111];
int a,b;
struct Node
{
int x,step;
Node(int _x,int _step)
{
x = _x;step = _step;
}
};
queue<Node> q;
int bfs(int x)
{
while(!q.empty()) q.pop();
q.push(Node(x,0));
while(!q.empty())
{
Node cur = q.front();
q.pop();
vis[cur.x] = 1;
if(cur.x == b)
return cur.step;
int tmp = cur.x;
for(int i = 0;i < 4;i++)
{
int digit = tmp%10;
tmp /= 10;
for(int j = (i==3? 1: 0);j < 10;j++)
{
if(j == digit) continue;
int xx = j*pow[i]+(cur.x-digit*pow[i]);
if(vis[xx]) continue;
if(is_prime[xx])
q.push(Node(xx,cur.step+1));
}
}
}
}
void init()
{
pow[0] = 1;
for(int i = 1;i < 4;i++)
{
pow[i] = pow[i-1]*10;
}
int N = 10000;
for (int i = 0 ; i < N; i ++)
{
is_prime[i] = 1;
}
is_prime[1] = 0;
for (int i = 2 ; i < N ; i ++)
{
if (! is_prime[i]) continue;
for (int j = 2 ; i*j < N ; j ++)
{
is_prime[i*j] = 0;
}
}
}
int main()
{
init();
int _;
scanf("%d",&_);
while(_--)
{
memset(vis,0,sizeof(vis));
scanf("%d%d",&a,&b);
printf("%d\n",bfs(a));
}
return 0;
}