poj 3126 Prime Path(bfs)
来源:互联网 发布:什么软件免费听音乐 编辑:程序博客网 时间:2024/06/08 09:11
题意:给两个四位素数,从第一个素数变换到第二个素数最少需要变换多少次,每次只变换一个位置上的数字,第一位数字不能为0
简单bfs
#include <cstdio>#include <cstring>#include <queue>using std::queue;struct node{ int val; int step;};bool prime[10000];bool book[10000];int s,e,res;int num[4];void getPrime(){ memset(prime,0,sizeof(prime)); prime[0] = prime[1] = true; for(int i = 2; i < 10000; ++i) { if(!prime[i]) for(int j = 2*i; j < 10000; j += i) prime[j] = true;//false表示是素数,true表示不是素数 }}bool isPrime(int num){ return !prime[num];}void BFS(){ memset(book,0,sizeof(book)); queue<node> que; node head; head.val = s; head.step = 0; book[s] = true; que.push(head); int temp; while(!que.empty()) { node cur = que.front(); que.pop(); if(cur.val == e) { res = cur.step; return; } num[0] = cur.val/1000; num[1] = (cur.val/100)%10; num[2] = (cur.val/10)%10; num[3] = cur.val%10; for(int i = 0; i < 4; ++i) { temp = num[i]; for(int j = 0; j < 10; ++j) { if(i == 0 && j == 0) continue; if(temp != j) { num[i] = j; int n = num[0]*1000+num[1]*100+num[2]*10+num[3]; if(!book[n] && isPrime(n)) { node atp; atp.val = n; atp.step = cur.step + 1; book[n] = true; que.push(atp); } } } num[i] = temp; } }}int main(){ int t; getPrime(); scanf("%d",&t); while(t--) { res = -1; scanf("%d %d",&s,&e); BFS(); if(res == -1) printf("Impossible\n"); else printf("%d\n",res); } return 0;}
0 0
- poj poj 3126 Prime Path(BFS)
- poj 3126 Prime Path(bfs搜索)
- POJ 3126 Prime Path (BFS)
- poj 3126 Prime Path(BFS)
- poj 3126 Prime Path (bfs)
- POJ 3126 Prime Path(BFS算法)
- Prime Path (poj 3126 bfs)
- POJ 3126 Prime Path(BFS)
- POJ 3126 - Prime Path(BFS)
- poj 3126 Prime Path(BFS)
- POJ 3126 Prime Path(BFS)
- POJ 3126 Prime Path (bfs、埃氏筛法)
- POJ 3126 Prime Path (BFS)
- POJ 3126 Prime Path(bfs)
- POJ 3126 Prime Path (BFS)
- POJ 3126 Prime Path (BFS)
- POJ 3126 Prime Path (BFS)
- POJ 3126 Prime Path(BFS)
- hdu 2923 Floyd
- 链表删除框架原理释义
- android实现定位与目的地的导航
- Android 主线程与子线程之间消息传递
- ES6学习手册(一)——初识ES6
- poj 3126 Prime Path(bfs)
- hdu 2050 折线分割平面
- Java中Runnable和Thread的区别
- 玲珑学院OJ 1091 Black and White【dp+前缀和】经典模型
- C++之模板详解(一)
- MySQL性能优化的最佳20+条经验
- 程序开发路线图
- sublime 一些好用的插件
- 无法打开物理文件 "f:\**.mdf"。操作系统错误 5:"5(拒绝访问。)