POJ 3126 Prime Path(素数判断+bfs)

题意:给你两个素数n,m,问最少多少步可以从n变为m?(1000<=  n,m  < 10000)每一步可以将n中的一位数字改变其他位不变,并且改变之后的数为素数。

思路:显然,n为起始状态,m为终止状态,用bfs找最短路。

#include <cstdio>
#include <algorithm>
#include <iostream>
#include<vector>
#include<cmath>
#include<set>
#include<cstring>
#include<sstream>
#include<queue>
#include<map>
using namespace std;
typedef long long ll;
const int maxn = 1299709 + 10;
const int maxt = 100200;
const int inf = 0x3f3f3f3f;
const ll INF = 0x7f7f7f7f7f7f7f7f;
const int mod = 1e9 + 7;
const double pi = acos(-1.0);
const double eps = 1e-8;
int n, m, k, t;
int vis[maxn];
int p[maxt];
int d[maxn];
void init(){
    for(int i = 2; i <= 10000; ++i){
        if(!vis[i]){
            for(int j = i + i; j <= 10000; j += i)
                vis[j] = 1;
        }
    }
    t = 0;
    for(int i = 1000; i < 10000; ++i)
        if(!vis[i]) p[t++] = i;
}
int ans[maxn];
void bfs(){
    queue<int> q;
    q.push(n);
    memset(d, 0, sizeof d);
    d[n] = 1;
    ans[n] = 0;
    while(!q.empty()){
        int x = q.front(); q.pop();
        if(x == m) {printf("%d\n", ans[m]); break;}
        int t1 = x % 10;
        int t2 = (x / 10) % 10;
        int t3 = (x / 100) % 10;
        int t4 = (x / 1000) % 10;
        int x1 = x - t1, x2 = x - t2 * 10, x3 = x - t3 * 100, x4 = x - t4 * 1000;
        for(int i = 0; i < 10; ++i){
            if(!vis[x1 + i] && i != t1 && !d[x1 + i]) {q.push(x1 + i); ans[x1 + i] = ans[x] + 1;d[x1 + i] = 1;}
            if(!vis[x2 + i * 10] && i != t2 && !d[x2 + i * 10]) {q.push(x2 + i * 10); ans[x2 + i * 10] = ans[x] + 1;d[x2 + i * 10] = 1;}
            if(!vis[x3 + i * 100] && i != t3 && !d[x3 + i * 100]) {q.push(x3 + i * 100); ans[x3 + i * 100] = ans[x] + 1;d[x3 + i * 100] = 1;}
            if(!vis[x4 + i * 1000] && i != t4 && i > 0 && !d[x4 + i * 1000]) {q.push(x4 + i * 1000); ans[x4 + i * 1000] = ans[x] + 1;d[x4 + i * 1000] = 1;}
        }
    }
}
int main(){
    init();
    int T;
    scanf("%d", &T);
    while(T--){
        scanf("%d%d", &n, &m);
        bfs();
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值