prime path

题目链接:https://vjudge.net/contest/203942#problem/F

题意就是让你将第一个数变成第二个数,每次只能变一个数字,然后,让你计算最少的次数,如果不可以变成另一个数的话就输出"Impossible",否则输出次数。

代码:

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<queue>
using namespace std;
int n,a,b;
int prime[10004]= {0};
int tag[10004]={0};
void init()//素数筛法,将所有素数都标记出来
{
    prime[1]=1;
    for(int i=2; i<=sqrt(10000); i++)
    {
        if(prime[i]==0)
        {
            for(int j=i+i; j<=10000; j+=i)
                prime[j]=1;
        }
    }
}
struct node
{
    int x;
    int step;
};
void bfs()
{
    node now,next;
    queue<node>q;
    now.x=a;
    now.step=0;
    q.push(now);
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        next.step=now.step+1;
        if(now.x==b)
        {
            printf("%d\n",now.step);
            return ;
        }
        for(int j=0; j<4; j++)
        {
            for(int i=0; i<=9; i++)
            {
                if(j==0)//个位
                    next.x=now.x-now.x%10+i;
                else if(j==1)//十位
                    next.x=now.x+(i-now.x%100/10)*10;
                else if(j==2)//百位
                    next.x=now.x+(i-now.x%1000/100)*100;
                else if(j==3&&i!=0)//千位,千位不能为0
                    next.x=now.x+(i-now.x/1000)*1000;
                if(prime[next.x]==0&&tag[next.x]==0)
                {
                    q.push(next);
                    tag[next.x]=1;
                }
            }
        }
    }
    printf("Impossible\n");
    return;
}
int main()
{
    init();
    scanf("%d",&n);
    while(n--)
    {
        memset(tag,0,sizeof(tag));
        scanf("%d%d",&a,&b);
        if(a==b)
        {
            printf("0\n");
            continue;
        }
        tag[a]=1;
        bfs();
    }
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值