【POJ3126】Prime Path

时间:2019-09-21
本文章向大家介绍【POJ3126】Prime Path,主要包括【POJ3126】Prime Path使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本题传送门

本题知识点:宽度优先搜索

题意很简单。要找一个质数变到另一个质数的最少步数,两个质数都是4位数,变的时候只能变其中一位,变了的数也仍是质数。

思路也很简单,对每一位数进行修改,如果修改后的数仍是质数则入队。

要注意的是千位数不能是0。

数据很小。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

int T;
int l, r;
bool take[100005];
struct node{
    int num;
    int t;
};
queue<node> que;
bool ok;

bool check(int n){
    for(int i = 2; i * i <= n; i++){
        if(n % i == 0) return false;
    }
    return true;
}

void bfs(){
    node a;
    a.num = l; a.t = 0;
    que.push(a);
    take[l] = true;

    while(!que.empty()){
        node next, now = que.front(); que.pop();
        int f;
//        printf("now num:%d t:%d   r:%d\n", now.num, now.t, r);
        if(now.num == r){
            printf("%d\n", now.t);
            ok = true;
            break;
        }

        // 个位
        f = now.num;
        f = f / 10 * 10;
        for(int i = 0; i <= 9; i++){
            int g = f + i;
            if(check(g) && !take[g]){
                next.num = g; next.t = now.t + 1;
                take[g] = true;
                que.push(next);
            }
        }

        // 十位
        f = now.num;
        f = f / 100 * 100 + f % 10;
        for(int i = 0; i <= 9; i++){
            int g = f + i * 10;
            if(check(g) && !take[g]){
                next.num = g; next.t = now.t + 1;
                take[g] = true;
                que.push(next);
            }
        }

        // 百位
        f = now.num;
        f = f / 1000 * 1000 + f % 100;
        for(int i = 0; i <= 9; i++){
            int g = f + i * 100;
            if(check(g) && !take[g]){
                next.num = g; next.t = now.t + 1;
                take[g] = true;
                que.push(next);
            }
        }

        // 千位
        f = now.num;
        f = f % 1000;
        for(int i = 1; i <= 9; i++){
            int g = f + i * 1000;
            if(check(g) && !take[g]){
                next.num = g; next.t = now.t + 1;
                take[g] = true;
                que.push(next);
            }
        }
    }
}

int main()
{
    scanf("%d", &T);
    while(T--){
        memset(take, false, sizeof(take));
        scanf("%d %d", &l, &r);
        while(!que.empty()) que.pop();
        ok = false;
        bfs();
        if(!ok) printf("Impossible\n");
    }
    return 0;
}

原文地址:https://www.cnblogs.com/Ayanowww/p/11561576.html