Prime Path poj 3126
来源:互联网 发布:孕妇孕期必备软件 编辑:程序博客网 时间:2024/06/06 07:35
大致题意:
给定两个四位素数a b,要求把a变换到b,变换的过程要保证 每次变换出来的数都是一个 四位素数,而且当前这步的变换所得的素数与前一步得到的素数,只能有一个位不同,而且每步得到的素数都不能重复。
求从a到b最少需要的变换次数。无法变换则输出Impossible
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <math.h>#include <stack>#include <queue>#include <vector>#include <iostream>#include <algorithm>using namespace std;#define maxn 15000struct num{ int prime; int step;};int a,b;bool visit[maxn];bool judge(int n){ if(n==2||n==3) return true; else if(n<=1||n%2==0) return false; else { for(int i=3;i*i<=n;i+=2) if(n%i==0) return false; return true; }}void bfs(){ queue<num> q; num x; x.prime=a; x.step=0; visit[x.prime]=true; q.push(x); while(!q.empty()) { num y=q.front(); q.pop(); if(y.prime==b) { printf("%d\n",y.step); return ; } int g=y.prime%10; int s=(y.prime/10)%10; for(int i=1;i<=9;i+=2) { x.prime=y.prime/10*10+i; if(x.prime!=y.prime&&!visit[x.prime]&&judge(x.prime)) { visit[x.prime]=true; x.step=y.step+1; q.push(x); } } for(int i=0;i<=9;i++) { x.prime=y.prime/100*100+i*10+g; if(x.prime!=y.prime&&!visit[x.prime]&&judge(x.prime)) { visit[x.prime]=true; x.step=y.step+1; q.push(x); } } for(int i=0;i<=9;i++) { x.prime=y.prime/1000*1000+i*100+s*10+g; if(x.prime!=y.prime&&!visit[x.prime]&&judge(x.prime)) { visit[x.prime]=true; x.step=y.step+1; q.push(x); } } for(int i=1;i<=9;i++) { x.prime=y.prime%1000+i*1000; if(x.prime!=y.prime&&!visit[x.prime]&&judge(x.prime)) { visit[x.prime]=true; x.step=y.step+1; q.push(x); } } } printf("Impossible\n"); return ;}int main(){ int t; scanf("%d",&t); while(t--) { scanf("%d%d",&a,&b); memset(visit,false,sizeof(visit)); bfs(); } 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
- 在Windows7中装Ubuntu双系统
- mysql 安装mysqlbackup
- 机器学习和人工智能将开创计算机2.0时代
- C语言 用递归法将一个整数n转换成字符串
- 数据库第五章作业
- Prime Path poj 3126
- 数的划分---动态规划
- js取出接口中json中数组里的值
- Unrecognised tag: 'encoding' (position: START_TAG seen ...</version>\r\n\t\t\t\t<encoding>... @12:15
- 黑马程序员——Java高新技术视频笔记:反射
- javascript设计模式理论和示例深入分析(下)
- 泛型(generic)颠倒数组中的所有元素
- 非常可乐 hdu 1495
- ZXing生成和解析带LOGO的二维码