poj3126——Prime Path

题目大意:给出两个四位素数,每次改变只能改四位中的一位,问最少经过几次改变能将第一个数变为第二个数

输入:case个数n(最多不超过100个)

           第i个case的两个四位素数(不以0开头)

输出:最少改变次数/impossible

分析:bfs搜索

           先打印素数表,再用队列进行bfs搜索。和leetcode127类似。这道题采用count数组记录每个结点的深度,而127没用count数组,而是直接记录遍历的层数,然后在每一层内广度遍历。

代码:转载自http://blog.csdn.net/wangjian8006/article/details/7461966

#include <iostream>  
#include <queue>  
using namespace std;  
#define MAXV 10000  
  
bool prime[MAXV];  
  
void init(){    //对素数打表  
    int i,j;  
    for(i=1000;i<=MAXV;i++){  
        for(j=2;j<i;j++)  
            if(i%j==0){  
                prime[i]=false;  
                break;  
            }  
        if(j==i) prime[i]=true;  
    }  
}  
  
int bfs(int first,int last){  
    bool dis[MAXV];  
    queue <int>q;  
    int v,i,j,temp,vtemp,count[MAXV],t[4];  
    memset(dis,false,sizeof(dis));  
    memset(count,0,sizeof(count));  
  
    q.push(first);  
    dis[first]=true;  
  
    while(!q.empty()){  
        v=q.front();  
        q.pop();  
        if(v==last) return count[v];  

        t[0]=v/1000;  
        t[1]=v%1000/100;  
        t[2]=v%100/10;  
        t[3]=v%10;  

        for(j=0;j<4;j++){  
            temp=t[j];//把第j位的数字先保存下来  
            for(i=0;i<10;i++)  
                if(i!=temp){  
                    t[j]=i;  
                    vtemp=t[0]*1000+t[1]*100+t[2]*10+t[3];  
                    if(!dis[vtemp] && prime[vtemp]){  
                        count[vtemp]=count[v]+1;  
                        dis[vtemp]=true;  
                        q.push(vtemp);  
                    }  
                }  
            t[j]=temp;  
        }  
    }  
    return -1;  
}  
  
int main(){  
    int n,a,b,key;  
    init();  
    scanf("%d",&n);  
    while(n--){  
        scanf("%d%d",&a,&b);  
        key=bfs(a,b);  
        if(key!=-1) printf("%d\n",key);  
        else printf("Impossible\n");  
    }  
    return 0;  
} 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值