POJ 3126 Prime Path
来源:互联网 发布:编程证明哥德巴赫猜想 编辑:程序博客网 时间:2024/06/05 11:27
给定两个四位素数a b,要求把a变换到b变换的过程要保证 每次变换出来的数都是一个 四位素数,而且当前这步的变换所得的素数 与 前一步得到的素数 只能有一个位不同,而且每步得到的素数都不能重复。 求从a到b最少需要的变换次数。无法变换则输出Impossible
解题思路:
超级水题,40入口的BFS + 素数判定
不过剪枝之后就没有40入口了,入口数远小于40
无论是判定素数还是搜索素数,首先排除偶数,这样就剪掉一半枝叶了
注意:千位的变换要保证千位不为0
其实素数也是用来辅助搜索剪枝的
#include<cstdio>#include<cstring>#include<cmath>#include<ctime>#include<algorithm>#include <iostream>#include <queue>#include <stack>#include <vector>#include <map>#include <set>#define INF 0x3f3f3f3f#define maxn 10010using namespace std;typedef long long ll;int cnt,a,b,num[maxn];struct node{ int x,step;}p,pp;int is_prime(int x){ for(int i = 2; i <= sqrt(x); i++) if(x % i == 0) return 0; return 1;}void BFS(int k){ queue<node> q; p.x = k; p.step = 0; q.push(p); while(!q.empty()) { p = q.front(); q.pop(); if(p.x == b) { printf("%d\n",p.step); return; } for(int i = 1; i < 10; i+=2) { int x = p.x; x = x / 10 * 10 + i; if(x != p.x && is_prime(x) && !num[x]) { num[x] = 1; pp.x = x; pp.step = p.step + 1; q.push(pp); } } for(int i = 0; i < 10; i++) { int x = p.x; int k = x % 10; x = x / 100 * 100 + i * 10 + k; if(x != p.x && is_prime(x) && !num[x]) { num[x] = 1; pp.step = p.step + 1; pp.x = x; q.push(pp); } } for(int i = 0; i < 10; i++) { int x = p.x; int k = x % 100; x = x / 1000 * 1000 + i * 100 + k; if(x != p.x && is_prime(x) && !num[x]) { num[x] = 1; pp.step = p.step + 1; pp.x = x; q.push(pp); } } for(int i = 1; i < 10; i++) { int x = p.x; int k = x % 1000; x = i * 1000 + k; if(x != p.x && is_prime(x) && !num[x]) { num[x] = 1; pp.step = p.step + 1; pp.x = x; q.push(pp); } } } printf("Impossible\n");}int main(){ int t; scanf("%d",&t); while(t--) { scanf("%d%d",&a,&b); cnt = INF; memset(num,0,sizeof(num)); num[a] = 1; BFS(a); } return 0;}
0 0
- POJ 3126 Prime Path
- POJ 3126 Prime Path
- poj 3126Prime Path
- POJ -3126-Prime Path
- POJ 3126 Prime Path
- poj 3126 Prime Path
- POJ 3126 - Prime Path
- POJ 3126 Prime Path
- poj 3126 prime path
- POJ 3126 Prime Path
- Prime Path poj 3126
- POJ 3126 Prime Path
- poj 3126 Prime Path
- POJ 3126 Prime Path
- poj 3126 Prime path
- poj - 3126 - Prime Path
- POJ 3126 Prime Path
- POJ 3126 Prime Path
- BAPI_GOODSMVT_CREATE
- Duilib界面库Capture系列的相关bug解决
- linux 编辑 php 扩展
- iOS UIWebView 无法确定web页面的真实高度
- android shape使用总结
- POJ 3126 Prime Path
- fork函数详解
- MEAN架构Angular fullstack generator生成器
- Introduction to Java Programming编程题6.1<为学生分数转换为ABCDF>
- JAVA IO流(2)
- 快速排序(Java)
- 基于Jenkins+git+gradle的android持续集成
- 1094. The Largest Generation
- js原生实现FastClick事件