POJ 3126 Prime Path(搜索)
2016-01-17 22:11
375 查看
AC代码:
#include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <string> #include <queue> using namespace std; struct node{ int pos,t; bool operator < (const node &a)const{ return t > a.t; } }; int prime[10005]; int vis[10005]; void is_prime(){ memset(prime,0,sizeof(prime)); for(int i = 1000; i < 10000; i++){ int tmp = sqrt(i*1.0),flag = 1; for(int j = 2; j <= tmp; j++){ if(i%j == 0){ flag = 0; break; } } if(flag) prime[i] = 1; } } int bfs(int a,int b){ memset(vis,0,sizeof(vis)); node cur; int num[4]; cur.pos = a;cur.t = 0; vis[a] = 1; priority_queue<node> q; q.push(cur); while(!q.empty()){ cur = q.top(); q.pop(); if(cur.pos == b){ return cur.t; } int tmppos = cur.pos; for(int i = 3; i >= 0; i--,tmppos/=10){ num[i] = tmppos%10; } for(int i = 0; i < 4; i++){ int tmp = num[i]; for(int j = 0; j < 10; j++){ if(num[i] != j){ num[i] = j; int pos = num[0]*1000+num[1]*100+num[2]*10+num[3]; if(prime[pos] && !vis[pos]){ vis[pos] = 1; q.push(node{pos,cur.t+1}); } } num[i] = tmp; } } } return -1; } int main(){ is_prime(); int T; scanf("%d",&T); while(T--){ int a,b; scanf("%d%d",&a,&b); int ans = bfs(a,b); if(ans < 0) printf("Impossible\n"); else printf("%d\n",ans); } return 0; }
相关文章推荐
- java 图片裁剪上传变红等失真现象、cmyk颜色模式图片裁剪异常现象处理
- Springmvc中@ResponseBody和@RequestBody的使用
- C++ std::vector元素的内存分配问题
- FFMPEG的用法
- PyCairo指南--基本绘图
- Android远程服务编写和调用教程
- 【转】将Oracle中的表结构导出到word
- Shader中“深度”的理解和思考(附例子)
- 虚拟机之 Wordpress博客搭建
- Hotspot JVM and GC basics studynote(1)
- POJ1426
- Tair ldb(leveldb存储引擎)实现介绍
- Spring MVC静态资源处理(转)
- 有用但偏僻的android资源
- Android SHA1与Package获取方式
- 几何求交点
- web前端响应式设计总结
- 修改 const 的值之后的奇怪变化
- 数列排序
- django 学习-17 Django会话Session