POJ3126 (bfs)
来源:互联网 发布:瑞珀网络机顶盒升级包 编辑:程序博客网 时间:2024/05/21 15:42
//题意给定两个四位数均是质数 由一个质数转化成另一个质数的最短步数 要求每次改变只能改变某一位上的数字 BFS即可
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "algorithm"
#include <queue>
using namespace std;
int prime[10001],ans[10001];
queue<int> que;
void creatlist()
{
memset(prime,0,sizeof prime);
for(int i=2;i<=10000;i++)
{
if(!prime[i])
for(int j=i<<1;j<=10000;j+=i)
prime[j]=1;
}
}
int main()
{
int t,op,ed,x1,x2,x3,x4,cnt;
scanf("%d",&t);
creatlist();
while(t--)
{
while(!que.empty())
que.pop();
memset(ans,0,sizeof ans);
scanf("%d%d",&op,&ed);
que.push(op);
ans[op]=0;
while(!que.empty())
{
int tmp=que.front();
if(tmp==ed)
break ;
que.pop();
x1=tmp%10;x2=tmp/10%10;x3=tmp/100%10;x4=tmp/1000;
for(int i=1;i<10;i++)
if(x4==i) continue;
else if(!prime[(i*1000+x3*100+x2*10+x1)]&&!ans[(i*1000+x3*100+x2*10+x1)])
{que.push((i*1000+x3*100+x2*10+x1));ans[(i*1000+x3*100+x2*10+x1)]=ans[tmp]+1;}
for(int i=0;i<10;i++)
if(x3==i) continue;
else if(!prime[(x4*1000+i*100+x2*10+x1)]&&!ans[(x4*1000+i*100+x2*10+x1)])
{que.push((x4*1000+i*100+x2*10+x1));ans[(x4*1000+i*100+x2*10+x1)]=ans[tmp]+1;}
for(int i=0;i<10;i++)
if(x2==i) continue;
else if(!prime[(x4*1000+x3*100+i*10+x1)]&&!ans[(x4*1000+x3*100+i*10+x1)])
{que.push((x4*1000+x3*100+i*10+x1));ans[(x4*1000+x3*100+i*10+x1)]=ans[tmp]+1;}
for(int i=0;i<10;i++)
if(x1==i) continue;
else if(!prime[(x4*1000+x3*100+x2*10+i)]&&!ans[(x4*1000+x3*100+x2*10+i)])
{que.push((x4*1000+x3*100+x2*10+i));ans[(x4*1000+x3*100+x2*10+i)]=ans[tmp]+1;}
}
printf("%d\n",ans[ed]);
}
return 0;
}
0 0
- POJ3126 BFS
- poj3126 bfs
- poj3126 bfs
- poj3126 BFS
- poj3126(bfs)
- poj3126 bfs
- POJ3126 (bfs)
- poj3126 - bfs
- poj3126(bfs)
- poj3126-prime+BFS
- 0.8poj3126(bfs)
- [POJ3126]Prime Path+BFS
- POJ3126 Prime Path(bfs)
- POJ3126 Prime Path(BFS)
- poj3126 prime path bfs
- bfs poj3126 Prime Path
- poj3126 Prime Path【bfs】
- poj3126 埃式筛法+bfs
- 安装最新的qt5.5.1,在使用qmake -v 出现qmake -v could not exec '/usr/lib/x86_64-linux-gnu/qt4/bin/qmake': No su
- 第一次用字符串
- HDU 4501 3重01背包
- Interview Q&A - 两个字符串整数相加返回和的字符串(C#)
- Java线程池及Future、Callable获得线程返回结果【Java线程池系列2】
- POJ3126 (bfs)
- 基于js与flash实现的网站flv视频播放插件代码
- 电源调试记录五
- recyclerview设置布局样式
- qt学习之QSting类型转换
- Wireless工具移植之wpa_supplicant
- 使用systemb过程
- 2015 CCPC C题(超时代码)
- 高级字符串查找