POJ 3126 Prime Path(基础搜索)

题目: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值