POJ 3126 Prime Path

给定两个四位素数a b,要求把a变换到b变换的过程要保证 每次变换出来的数都是一个 四位素数,而且当前这步的变换所得的素数 与 前一步得到的素数 只能有一个位不同,而且每步得到的素数都不能重复。 求从a到b最少需要的变换次数。无法变换则输出Impossible

解题思路:

超级水题,40入口的BFS + 素数判定

不过剪枝之后就没有40入口了,入口数远小于40

无论是判定素数还是搜索素数,首先排除偶数,这样就剪掉一半枝叶了

注意:千位的变换要保证千位不为0

      其实素数也是用来辅助搜索剪枝的


#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include <iostream>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#define INF 0x3f3f3f3f
#define maxn 10010
using namespace std;
typedef long long ll;
int cnt,a,b,num[maxn];
struct node
{
    int x,step;
}p,pp;
int is_prime(int x)
{
    for(int i = 2; i <= sqrt(x); i++)
        if(x % i == 0)
            return 0;
    return 1;
}
void BFS(int k)
{
    queue<node> q;
    p.x = k;
    p.step = 0;
    q.push(p);
    while(!q.empty())
    {
        p = q.front();
        q.pop();
        if(p.x == b)
        {
            printf("%d\n",p.step);
            return;
        }
        for(int i = 1; i < 10; i+=2)
        {
            int x = p.x;
            x = x / 10 * 10 + i;
            if(x != p.x && is_prime(x) && !num[x])
            {
                num[x] = 1;
                pp.x = x;
                pp.step = p.step + 1;
                q.push(pp);
            }
        }
        for(int i = 0; i < 10; i++)
        {
            int x = p.x;
            int k = x % 10;
            x = x / 100 * 100 + i * 10 + k;
            if(x != p.x && is_prime(x) && !num[x])
            {
                num[x] = 1;
                pp.step = p.step + 1;
                pp.x = x;
                q.push(pp);
            }
        }
        for(int i = 0; i < 10; i++)
        {
            int x = p.x;
            int k = x % 100;
            x = x / 1000 * 1000 + i * 100 + k;
            if(x != p.x && is_prime(x) && !num[x])
            {
                num[x] = 1;
                pp.step = p.step + 1;
                pp.x = x;
                q.push(pp);
            }
        }
        for(int i = 1; i < 10; i++)
        {
            int x = p.x;
            int k = x % 1000;
            x = i * 1000 + k;
            if(x != p.x && is_prime(x) && !num[x])
            {
                num[x] = 1;
                pp.step = p.step + 1;
                pp.x = x;
                q.push(pp);
            }
        }
    }
    printf("Impossible\n");
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&a,&b);
        cnt = INF;
        memset(num,0,sizeof(num));
        num[a] = 1;
        BFS(a);
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值