Prime Path------poj3126

 

题目大意:

                给定两个素数a b,求a变幻到b需要几步
                并且变幻时只有一个数字不同,并且是素数

解题思路:

              因为是四位的素数,所以先对素数打表,然后BFS,每次进入队列的是八个只有一个数字不同的四位数,并且还要是素数就入队

#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <queue>
using namespace std;
const int maxn = 1e5;

bool prime[maxn];
//素数打表
void init()
{
    int i, j;
    for(i = 1000; i <= maxn; ++i)
    {
        bool flag = true;
        for(j = 2; j <= sqrt(i); ++j)
            if(i % j == 0)
            {
                prime[i] = false;
                flag = false;
                break;
            }
        if(flag) prime[i] = true;
    }
}
//广搜
int bfs(int first, int last)
{
    bool dis[maxn];
    queue<int> q;
    int count[maxn], t[4];
    memset(dis, false, sizeof(dis));
    memset(count, 0, sizeof(count));

    q.push(first);
    dis[first] = true;

    while(!q.empty())
    {
        int v = q.front();
        q.pop();

        t[0] = v / 1000;
        t[1] = v % 1000 / 100;
        t[2] = v % 100 / 10;
        t[3] = v % 10;

        //改变每一位构造素数
        for(int j = 0; j < 4; ++j)
        {
            //保存要变的数
            int temp = t[j];
            //枚举
            for(int i = 0; i < 10; ++i)
                if(i != temp)
                {
                    t[j] = i;
                    //新的四位数
                    int vt = t[0]*1000+t[1]*100+t[2]*10+t[3];
                    //没有用过且是素数
                    if(!dis[vt] && prime[vt])
                    {
                        //到vt要几步
                        count[vt] = count[v] + 1;
                        //true表示用过
                        dis[vt] = true;
                        //将构造出的素数放进队列
                        q.push(vt);
                    }
                    //如果构造出的数是目标,返回步数
                    if(vt == last) return count[vt];
                }
            //回溯,将改变的那位数变回来
            t[j] = temp;
        }
        if(v == last) return count[v];
    }
    return -1;
}

int main()
{
    int n;
    init();
    cin >> n;
    while(n--)
    {
        int a, b;
        cin >> a >> b;
        int key = bfs(a, b);
        //cout << key << endl;
        if(key != -1) cout << key << endl;
        else cout << "Impossible\n";
    }
    return 0;
}
/*
Sample Input

    3
    1033 8179
    1373 8017
    1033 1033

Sample Output

    6
    7
    0
*/

 

转载于:https://my.oschina.net/Userxs/blog/1618192

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值