[toj2648 **BFS**]**Prime Path**

toj2648-Prime Path解题报告

  • 我只是想玩一下这个新粗来的编辑器,终于等来了,^_^哈哈~…

Prime Path
给两个数ab,每次操作仅可以改变一位数并且中间数只能是质数,问经过多少步可以从a变到b
思路:BFS简单搜索一下即可.

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

struct node {
    int a;
    int step;
    bool operator==(const node& b)const {
        return b.a == a;
    }
} otst, dest;
const int MAX = 10007;
bool vis[MAX];
bool isPrime[MAX];
int eNext[5] = {1, 10, 100, 1000, 10000};

int BFS() {
    memset(vis, false, sizeof(vis));
    vis[otst.a] = true;
    queue<node> Q;
    Q.push(otst);
    while (!Q.empty()) {
        node now = Q.front(), next;
        Q.pop();
        if (now == dest) {
            return now.step;
        }

        int num[4], tmp = now.a;
        for (int i = 0; i < 4; ++i) {
            num[i] = tmp % 10;
            tmp /= 10;
        }
        next.step = now.step + 1;
        for (int i = 0; i < 4; ++i) {
            for (int j = 1; j < 10; ++j) {
                   int mNext[4];
                   memcpy(mNext, num, sizeof(num));
                   mNext[i] = (num[i] + j) % 10;
                   tmp = 0;
                   for (int i = 3; i >= 0; --i) {
                       tmp *= 10;
                       tmp += mNext[i];
                   }
                   if (tmp > 999 && isPrime[tmp] && !vis[tmp]) {
                       vis[tmp] = true;
                       next.a = tmp;
                       Q.push(next);
                   }
            }
        }//for
    }//while
    return -1;
}

int main() {
    memset(isPrime, true, sizeof(isPrime));
    for (int i = 2; i < MAX / i; ++i) {
        for (int j = i * i; j < MAX; j += i) {
            isPrime[j] = false;
        }
    }

    int T, a, b;
    scanf(" %d", &T);
    while (T--) {
        scanf(" %d %d", &a, &b);
        otst.a = a, otst.step = 0;
        dest.a = b;
        int ans = BFS();
        if (ans == -1) {
            puts("Impossible");
        } else {
            printf("%d\n", ans);
        }
    }
    return 0;
}
  • 试用了一下
    • 还是很棒!!!
      • 有木有?!!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值