POJ 3126 Prime Path 简单广搜(BFS)
2024-09-04 05:58:13
题意:一个四位数的质数,每次只能变换一个数字,而且变换后的数也要为质数。给出两个四位数的质数,输出第一个数变换为第二个数的最少步骤。
利用广搜就能很快解决问题了。还有一个要注意的地方,千位要大于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;
}
最新文章
- 缓存工厂之Redis缓存
- 如何在Mac OS X中显示隐藏的文件
- Intent组件的传参应用
- Asp.net窄屏页面 手机端新闻列表
- hdu3966 树链剖分+成段更新
- 微信聊天测试脚本 wx_sample.php
- InputStream和OutputStream与String之间的转换
- selenium--大家庭介绍
- 《WPF程序设计指南》读书笔记——第6章 Dock与Grid
- Python[1,1]
- 版本控制——TortoiseSVN (4)多版本并行开发 B
- C++ 模板基础
- .net core使用Pipelines进行消息IO合并
- VB代码收集
- maven作用
- spring对bean的高级装配之基于@Conditional条件化装配
- Irrlicht 3D Engine 笔记系列 之 自己定义Animator
- 阿里百川码力APP监控 来了!
- C# 遍历枚举(枚举是目的,遍历(获取)是手段)
- jQuery入门简单实现反选与全选