题意:一个四位数的质数,每次只能变换一个数字,而且变换后的数也要为质数。给出两个四位数的质数,输出第一个数变换为第二个数的最少步骤。

利用广搜就能很快解决问题了。还有一个要注意的地方,千位要大于0。例如0373这个数不符合要求。

#include <iostream>
#include <cstdio>
#include <queue>
#include <cmath>
#include <map>
using namespace std; struct Struct
{
int num;
int step;
};
bool Prime(int a) //判断是否为质数
{
for(int i=2;i<=sqrt(a);i++)
if(a%i==0)
return false;
return true;
}
int bfs(int a,int b)
{
queue<Struct>q;
map<int,bool>m; //用map来标记数字是否被访问过
Struct temp,next;
temp.num=a;
temp.step=0;
m[a]=true;
q.push(temp);
while(!q.empty())
{
temp=q.front();
if(temp.num==b)
return temp.step;
q.pop();
for(int i=1;i<10;i++) //变换千位
{
next=temp;
next.num=next.num%1000+i*1000;
if(!m[next.num] && Prime(next.num))
{
m[next.num]=true;
next.step++;
q.push(next);
}
}
int x=100;
for(int i=0;i<3;i++) //变换百位,十位,个位
{
for(int j=0;j<10;j++)
{
next=temp;
next.num=next.num%x+j*x+next.num/(x*10)*(x*10);
if(!m[next.num] && Prime(next.num))
{
m[next.num]=true;
next.step++;
q.push(next);
}
}
x=x/10;
}
}
return -1;
}
int main()
{
//freopen("in.txt","r",stdin);
int n;
scanf("%d",&n);
while(n--)
{
int a,b;
scanf("%d%d",&a,&b);
int ans=bfs(a,b);
if(ans!=-1)
printf("%d\n",ans);
else
printf("Impossible\n");
}
return 0;
}

最新文章

  1. 缓存工厂之Redis缓存
  2. 如何在Mac OS X中显示隐藏的文件
  3. Intent组件的传参应用
  4. Asp.net窄屏页面 手机端新闻列表
  5. hdu3966 树链剖分+成段更新
  6. 微信聊天测试脚本 wx_sample.php
  7. InputStream和OutputStream与String之间的转换
  8. selenium--大家庭介绍
  9. 《WPF程序设计指南》读书笔记——第6章 Dock与Grid
  10. Python[1,1]
  11. 版本控制——TortoiseSVN (4)多版本并行开发 B
  12. C++ 模板基础
  13. .net core使用Pipelines进行消息IO合并
  14. VB代码收集
  15. maven作用
  16. spring对bean的高级装配之基于@Conditional条件化装配
  17. Irrlicht 3D Engine 笔记系列 之 自己定义Animator
  18. 阿里百川码力APP监控 来了!
  19. C# 遍历枚举(枚举是目的,遍历(获取)是手段)
  20. jQuery入门简单实现反选与全选

热门文章

  1. 服务器硬件必须支持M2 或PCIE才能支持NVME
  2. 使用 dd 命令进行硬盘 I/O 性能检测
  3. Hive 安装和配置
  4. 云计算OpenStack核心组件---keystone身份认证服务(5)
  5. 常用数据库连接池配置及使用(Day_11)
  6. wxPython开发之密码管理程序
  7. 【python接口自动化】初识unittest框架
  8. 初遇SpringBoot踩坑与加载静态文件遇到的坑
  9. xtrabackup(innobackupex)使用详解
  10. synchronized使用及java中的原子性问题