POJ3126 Prime Path

要注意筛素数的时候要小于等于
第一次wa原因是有的是合数而判断为素数

//总体思路 先打一张素数表 之后从千位开始改变状态 进行bfs
#include<iostream>
#include<queue>
#define MAX 10001
using namespace std;
bool prime[MAX];                //打一张素数表
int dis[MAX];
void init();
void bfs(int const begin, int const end);
int main()
{
    int begin, end,T;
    cin >> T;
    while (T--)
    {
        cin >> begin >> end;
        init();
        memset(dis, -1, sizeof(dis));
        bfs(begin, end);        
        if (dis[end] == -1)
            cout << "Impossible" << endl;
        else
            cout << dis[end] << endl;
    }
}
void init()
{
    int i,j;
    for (i = 1000; i < 10001; i++)
    {
        for (j = 2; j*j <= i; j++)
        {
            if (i%j == 0)
            {
                prime[i] = false;
                break;
            }
        }
        if (j*j > i)
            prime[i] = true;
    }
    return;
}
void bfs(int  begin, int  end)
{
    queue<int>que;
    que.push(begin);
    dis[begin] = 0;
    prime[begin] = false;
    while (que.size())
    {
        int temp = que.front(), temp1, i;
        int a, b, c, d;                         //分离各位数字 分别代表千百十个  剪枝思路:个位不能是偶数和五 
        a = temp / 1000;
        b = temp / 100 % 10;
        c = temp / 10 % 10;
        d = temp % 10;
        if (end == temp)
            return;
        for (i = 1; i <= 9; i++)            //对千位BFS
        {
            temp1 = i * 1000 + b * 100 + c * 10 + d;
            if (temp1 <= 10000 && i != a && prime[temp1])
            {
                que.push(temp1);
                prime[temp1] = false;
                dis[temp1] = dis[temp] + 1;
            }
        }
        for (i = 0; i <= 9; i++)            //百位BFS
        {
            temp1 = a * 1000 + i * 100 + c * 10 + d;
            if (temp1 <= 10000 && i != b && prime[temp1])
            {
                que.push(temp1);
                prime[temp1] = false;
                dis[temp1] = dis[temp] + 1;
            }
        }
        for (i = 0; i <= 9; i++)             //十位BFS
        {
            temp1 = a * 1000 + b * 100 + i * 10 + d;
            if (temp1 <= 10000 && i != c && prime[temp1])
            {
                que.push(temp1);
                prime[temp1] = false;
                dis[temp1] = dis[temp] + 1;
            }
        }
        for (i = 1; i <= 9; i = i + 2)
        {
            temp1 = a * 1000 + b * 100 + c * 10 + i;
            if (temp1 <= 10000 && i != 5 && i != c && prime[temp1])
            {
                que.push(temp1);
                prime[temp1] = false;
                dis[temp1] = dis[temp] + 1;
            }
        }
        que.pop();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值