POJ-3126 Prime Path ( BFS )

本文分享了一个关于在素数间通过BFS算法寻找最短转换路径的问题解决方案。该问题涉及构建素数表、广度优先搜索算法的应用,并提供了一段实现代码作为参考。

很套路的 bfs 

数据也挺水(要不就是这个题目存在规律性) 上 ac 代码,欢迎审阅

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<set>
#include<queue>
using namespace std;
const int maxn = 10000 + 10;
const int INF = 1e9 +7;
typedef long long LL;
int a[maxn], vis[maxn];
int n, x, y;

struct mes {
    int v;
    int cnt;
};
queue<mes> qu;

void prep() {    // 打表
    memset(a, 0, sizeof a);
    a[1] = 1;
    for(int i = 2; i < 10000; ++i) {
        if(a[i] == 0) {
            for(int j = 2*i; j < 10000; j += i)
                a[j] = 1;
        }
    }
}

int bfs(int s) {
    if(s == y) return 0;

    while(!qu.empty()) qu.pop();
    memset(vis, 0, sizeof vis);
    vis[s] = 1;
    qu.push((mes){s, 0});

    while(!qu.empty()) {
        mes t = qu.front(); qu.pop();
        for(int i = 1; i <= 1000; i *= 10) {
            for(int j = 0; j < 10; ++j) {
                if(i == 1000 && j == 0) continue;
                int d = t.v%i + j*i + t.v/(i*10)*(i*10);
                if(d == y) return t.cnt+1;
                if(a[d] == 0) {  // 是素数
                    if(vis[d]) continue;
                    vis[d] = 1;
                    qu.push((mes){d, t.cnt+1} );
                }
            }
        }
    }
    return -1;
}

int main() {
    prep();
    scanf("%d", &n);
    while(n--) {
        scanf("%d%d", &x, &y);
        int ans = bfs(x);
        if(ans == -1) cout << "Impossible" << endl;
        else cout << ans << endl;
    }
    return 0;
}


/*
3
1033 8179
1373 8017
1033 1033
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值