poj3126 Prime Path BFS深度优先搜索

bfs水题,直接上代码。(Why?怎么有没有写替罪羊树,算了,写了这一篇就写替罪羊树吧?如果你不知道我在说什么,看博客:http://blog.csdn.net/ljf_cnyali/article/details/52588684
好了,代码如下:
这是什么时候写的,时间貌似又不对耶!

/*************************************************************************
    > File Name: poj\poj_3126.cpp
    > Author: ljf_cnyali
    > Mail: 2724424647@qq.com
    > Last modifiedz: 2016-08-26 20:41
    > Description: This is a large group of God's program information.
 ************************************************************************/

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<ctime>
#include<algorithm>
#include<queue>
#include<map>
#include<set>
#include<ctime>

using namespace std;

#define REP(i, a, b) for(int i = (a), _end_ = (b);i <= _end_; ++i)

const int maxn = 10000;

int f[maxn], vis[maxn];

struct node {
    int x, s; 
};

void INIT() {
    REP(i, 1, 9999)
        f[i] = 1;
    REP(i, 2, 9999)
        if(f[i])
            for(int j = i * 2;j <= 9999; j += i)
                f[j] = 0;
}

int x, y;

void BFS() {
    if(x == y) {
        printf("0\n");
        return;
    }
    queue<node> q;
    memset(vis, 0, sizeof(vis));
    vis[x] = true;
    q.push((node){x, 0});
    while(!q.empty()) {
        node p = q.front(); 
        q.pop();
        for(int i = 1;i <= 1000; i *= 10) {
            REP(j, 0, 9) {
            if(i == 1000 && j == 0) 
                    continue;
            int t = p.x % i + j * i + p.x / (i * 10) * (i * 10);
            if(t == y) {
                    printf("%d\n", p.s + 1);
                    return;
                }
            if(f[t]) {
                if(vis[t])
                    continue;
                vis[t] = true;
                q.push((node){t, p.s + 1});
            }
        }
        }
    }
    printf("-1\n");
}

int main() {
    INIT();
    int n;
    scanf("%d", &n);
    while(n--) { 
        scanf("%d%d", &x, &y);
        BFS();
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值