POJ.3126 Prime Path (BFS)

POJ.3126 Prime Path (BFS)

题意分析

给出一个四位的起始素数sta和一个四位的终止素数end, 保证end>=sta. 每次我们可以对这个sta变化它的一位,使得它变成一个新的数字,但是这个数字必须是素数。求得从sta变到end最小的操作次数。

首先需要打一个10000级别素数表,然后我们每次对数字bfs,枚举它的每一位,并且枚举每一位的所有情况,从0-9.因为素数并不是很多,所以不用担心有很多元素会进入bfs的队列。

每次取队首,如果发现就是最后的end,终止输出最后变化次数即可。

代码总览

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <cmath>
#define nmax 5
using namespace std;
typedef struct{
    int digit[nmax];
    int times;
}dig;
int t,sta,end,ans;
int st[nmax],ed[nmax];
int visit[10000];
void init()
{
    memset(visit,0,sizeof(visit));
    for(int i = 2;i<(int)sqrt(10000);++i){
        for(int j = 2;i*j<10000;++j){
            visit[i*j] = true;
        }
    }
}

void converToSz()
{
    int temp  = sta;
    int pos = 0;
    while(temp !=0 ){
        st[pos++] = temp % 10;
        temp/=10;
    }
    temp = end;
    pos = 0;
    while(temp != 0){
        ed[pos++] = temp % 10;
        temp /= 10;
    }
}
int converToNum(dig temp)
{
    int base = 1;
    int sum = 0;
    for(int i = 0;i<4;++i){
        sum+= base * temp.digit[i];
        base*=10;
    }
    return sum;
}
bool check(dig temp)
{
    int num  = converToNum(temp);
    if(num < 1000 || visit[num]) return false;
    else return true;
}
void bfs()
{
    queue<dig> q;
    while(!q.empty()) q.pop();
    dig temp = {st[nmax],0},head;
    for(int i = 0;i<4;++i) temp.digit[i] = st[i];
    temp.times = 0;
    q.push(temp);
    visit[sta] = true;
    while(!q.empty()){
        head = q.front();q.pop();
        int pw = converToNum(head);
        //printf("%d\n",pw);
        if(pw == end){
            ans = head.times;
            return;
        }
        for(int i = 0;i<4;++i){
            temp = head;
            temp.times = head.times+1;
            for(int j = 0;j<10;++j){
                temp.digit[i] = j;
                if(check(temp)){
                    visit[converToNum(temp)] = converToNum(head);
                    q.push(temp);
                }
            }
        }
    }
}
void output()
{
    int temp = end;
    while(visit[temp] != true){
        printf("%d\n",temp);
        temp = visit[temp];
    }
}
int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    scanf("%d",&t);
    while(t--){
        scanf("%d %d",&sta,&end);
        init();
        converToSz();
        bfs();
       // output();
        printf("%d\n",ans);
    }
    return 0;
}
posted @ 2017-07-28 23:30  pengwill  阅读(97)  评论(0编辑  收藏  举报