POJ 3126-Prime Path(BFS)
2015-08-16 15:59
417 查看
题目地址:POJ 3126
题意:给你两个4位的都是素数正整数n,m,每次可以变 个十百千位 中的一个数(变化后也是素数,问最少经过多少次变化n能变成m,如果不能输出Impossible(窝觉得并没有不成立的情况
思路:每次变化一位,然后搜就好了。
题意:给你两个4位的都是素数正整数n,m,每次可以变 个十百千位 中的一个数(变化后也是素数,问最少经过多少次变化n能变成m,如果不能输出Impossible(窝觉得并没有不成立的情况
思路:每次变化一位,然后搜就好了。
#include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <iostream> #include <sstream> #include <algorithm> #include <set> #include <queue> #include <stack> #include <map> #pragma comment(linker, "/STACK:102400000,102400000") using namespace std; typedef __int64 LL; const int inf=0x3f3f3f3f; const double pi= acos(-1.0); const double esp=1e-7; const int Maxn=1e6+10; struct node { int x1,x2,x3,x4; int cnt; }q[Maxn],f1,f2; int n,m; int vis[Maxn]; int isprime(int x) { for(int i=2;i<=sqrt(x);i++) if(x%i==0) return 0; return 1; } void BFS() { memset(vis,0,sizeof(vis)); queue<node >q; f1.x1=n%10,n/=10; f1.x2=n%10,n/=10; f1.x3=n%10,n/=10; f1.x4=n; f1.cnt=0; vis =1; q.push(f1); while(!q.empty()){ f1=q.front(); q.pop(); if(f1.x4*1000+f1.x3*100+f1.x2*10+f1.x1==m){ printf("%d\n",f1.cnt); return ; } for(int i=1;i<=9;i++){ if(i!=f1.x4){ int tmp=i*1000+f1.x3*100+f1.x2*10+f1.x1; if(isprime(tmp)&&!vis[tmp]){ vis[tmp]=1; f2.x4=i; f2.x3=f1.x3; f2.x2=f1.x2; f2.x1=f1.x1; f2.cnt=f1.cnt+1; q.push(f2); } } } for(int i=0;i<=9;i++){ if(i!=f1.x3){ int tmp=f1.x4*1000+i*100+f1.x2*10+f1.x1; if(isprime(tmp)&&!vis[tmp]){ vis[tmp]=1; f2.x4=f1.x4; f2.x3=i; f2.x2=f1.x2; f2.x1=f1.x1; f2.cnt=f1.cnt+1; q.push(f2); } } } for(int i=0;i<=9;i++){ if(i!=f1.x2){ int tmp=f1.x4*1000+f1.x3*100+i*10+f1.x1; if(isprime(tmp)&&!vis[tmp]){ vis[tmp]=1; f2.x4=f1.x4; f2.x3=f1.x3; f2.x2=i; f2.x1=f1.x1; f2.cnt=f1.cnt+1; q.push(f2); } } } for(int i=0;i<=9;i++){ if(i!=f1.x3){ int tmp=f1.x4*1000+f1.x3*100+f1.x2*10+i; if(isprime(tmp)&&!vis[tmp]){ vis[tmp]=1; f2.x4=f1.x4; f2.x3=f1.x3; f2.x2=f1.x2; f2.x1=i; f2.cnt=f1.cnt+1; q.push(f2); } } } } puts("Impossible"); return ; } int main() { int T; scanf("%d",&T); while(T--){ scanf("%d %d",&n,&m); BFS(); } return 0; }
相关文章推荐
- IOS- 笔记2(闭包应用例)
- 黑马程序员-----java基础之构造方法
- php:文件系统②
- 【日常学习】【划分DP】codevs1017 乘积最大题解
- hadoop的安全模式
- 编写高质量代码改善C#程序的157个建议——建议51:具有可释放字段的类型或拥有本机资源的类型应该是可释放的
- 黑马程序员 环境的配置问题
- hdu 5389 Zero Escape DP+数学规律 给出证明 2015 Multi-University Training Contest 8
- UVALive 5107 dfs暴力搜索
- C语言 extern3 全局变量的使用
- HDU-1226 超级密码 (BFS+剪枝)
- mysql安装版和解压版安装过程遇到1067的问题,和数据库乱码问题 解决办法
- python 点滴记录14:join()方法
- android图片网络异步加载显示
- 循序渐进学java 13种核心技术
- 写给新手程序员的一封信
- java中的异常机制(编译时异常)
- Java 实现的内容搜索工具
- Openstack Integration with VMware vCenter by Devstack and Opencontrail
- webservices客户端调用