2021-04-01

Prime Path

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<queue>

using namespace std;
struct node{
    int date,s;
};
int n,m;
int book[100000]; //记录是否访问过
int Prime(int x){           //判断素数
    if(x<=1) return 0;
    if(x==2||x==3) return 1;
    int i;
    for(i=2;i<=sqrt(x);i++)
        if(x%i==0) return 0;
    return 1;
}
int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        memset(book,0,sizeof(book));
        scanf("%d%d",&n,&m);
        if(n==m){
            printf("0\n");
            continue;
        }
        node stemp;
        stemp.date=n;
        stemp.s=0;
        book[n]=1;
        queue<node>p;
        p.push(stemp);
        int f=0;
        while(!p.empty()){
            stemp=p.front();
            int i;
            for(i=1;i<=9;i=i+2){            //个位
                int tx=stemp.date/10*10+i;
                if(tx==m){
                    f=stemp.s+1;
                    break;
                }
                if(book[tx]==0&&Prime(tx)){
                    book[tx]=1;
                    node stem;
                    stem.date=tx;
                    stem.s=stemp.s+1;
                    p.push(stem);
                }
            }
             for(i=0;i<=9;i++){              // 十位
                int tx=stemp.date/100*100+i*10+stemp.date%10;
                if(tx==m){
                    f=stemp.s+1;
                    break;
                }
                if(book[tx]==0&&Prime(tx)){
                    book[tx]=1;
                    node stem;
                    stem.date=tx;
                    stem.s=stemp.s+1;
                    p.push(stem);
                }
            }
             for(i=0;i<=9;i++){           //百位
                int tx=stemp.date/1000*1000+i*100+stemp.date%100;
                if(tx==m){
                    f=stemp.s+1;
                    break;
                }
                if(book[tx]==0&&Prime(tx)){
                    book[tx]=1;
                    node stem;
                    stem.date=tx;
                    stem.s=stemp.s+1;
                    p.push(stem);
                }
            }
             for(i=1;i<=9;i++){            //千位
                int tx=stemp.date%1000+i*1000;
                if(tx==m){
                    f=stemp.s+1;
                    break;
                }
                if(book[tx]==0&&Prime(tx)){
                    book[tx]=1;
                    node stem;
                    stem.date=tx;
                    stem.s=stemp.s+1;
                    p.push(stem);
                }
            }
            if(f) break;
            p.pop();
        }
        if(f) printf("%d\n",f);
        else printf("Impossible\n");
    }
return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值