POJ 3126 素数+广搜

题意:给你两个四位的素数,从 n - > m 要变换几回...

思路:素数打表 + 广搜,因为好久没写搜索了,所以卡了好久才1过了,

用一般的对列,再用一个数组记录它的步数,就OK了..

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
#define manx 25000
int n,m,pos[manx],mark[manx],flag;
bool s[manx];
void prime(){
    memset(s,0,sizeof(s));
    for(int i=2;i*i<manx;i++){
        if(!s[i]){
            for(int j=2;j*i<manx;j++){
                s[i*j]=1;
            }
        }
    }
}
void bfs(){
    memset(pos,0,sizeof(pos));
    memset(mark,0,sizeof(mark));
    queue<int>que;
    while(!que.empty())  que.pop();
    que.push(n);
    mark[n]=1;
    while(!que.empty()){
        if(que.front()==m) {
            flag=1;
            printf("%d\n",pos[m]);
            break;
        }
        int temp=que.front();
        que.pop();
        for(int i=0;i<=9;i++){
            if(!s[temp/10*10+i] && !mark[temp/10*10+i]){ /// 处理个位 
                mark[temp/10*10+i]=1;
                que.push(temp/10*10+i);
                pos[temp/10*10+i]=pos[temp]+1;
            }        
            if(!s[temp/100*100+temp%10+i*10] && !mark[temp/100*100+temp%10+i*10]) { /// 处理十位
                mark[temp/100*100+temp%10+i*10]=1;
                que.push(temp/100*100+temp%10+i*10);
                pos[temp/100*100+temp%10+i*10]=pos[temp]+1;
            }   
            if(!s[temp/1000*1000+temp%100+i*100] && !mark[temp/1000*1000+temp%100+i*100]) { /// 处理百位
                mark[temp/1000*1000+temp%100+i*100]=1;
                que.push(temp/1000*1000+temp%100+i*100);
                pos[temp/1000*1000+temp%100+i*100]=pos[temp]+1;
            }
            if(!s[temp%1000+i*1000] && !mark[temp%1000+i*1000] && temp%1000+i*1000>=1000){ /// 处理千位
                mark[temp%1000+i*1000]=1;
                que.push(temp%1000+i*1000);
                pos[temp%1000+i*1000]=pos[temp]+1;
            }
        }
    }
}
int main(){
    prime();
    int t;
    scanf("%d",&t);
    while(t--){
        scanf("%d%d",&n,&m);
        flag=0;
        bfs();
        if(!flag) printf("Impossible\n");
    }
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值