poj3126 Prime Path BFS深度优先搜索

来源:互联网 发布:js单选框选中触发事件 编辑:程序博客网 时间:2024/06/04 17:40

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
原创粉丝点击