【poj 3126】Prime Path 题意&题解&代码(C++)
来源:互联网 发布:仿163k地方门户 源码 编辑:程序博客网 时间:2024/04/29 07:26
题目链接:
http://poj.org/problem?id=3126
题意:
给定两个四位素数a b,要求把a变换到b
变换的过程要保证 每次变换出来的数都是一个 四位素数,而且当前这步的变换所得的素数 与 前一步得到的素数 只能有一个位不同,而且每步得到的素数都不能重复。
求从a到b最少需要的变换次数。无法变换则输出Impossible
题解:
bfs搜索,每次将可以改到的值添进队列,直到搜出答案,注意找出将x改某一位数字得到y的公式,筛个素数表,方便判断。
代码:
#include<iostream>#include<algorithm>#include<stdio.h>#include<string.h>#include<queue>using namespace std;int T,dis[10005],a,b,isp[10005];queue<int>q;int main(){ for (int i=3;i<=10005;i++) for (int j=2;j*j<=i;j++) if (i%j==0) isp[i]=1; scanf("%d",&T); while(T--) { memset(dis,-1,sizeof(dis)); while(!q.empty()) q.pop(); scanf("%d%d",&a,&b); q.push(a);dis[a]=0; while(!q.empty() && dis[b]==-1) { int now=q.front();q.pop(); cout<<now<<endl; int tmp=1; for (int k=1;k<=4;k++) { for (int i=0;i<=9;i++) { if (k==4 && i==0) continue; int nex=(now/(tmp*10))*(tmp*10)+tmp*i+now%tmp;// cout<<nex<<endl; if (!isp[nex] && dis[nex]==-1) { dis[nex]=dis[now]+1; q.push(nex); } } tmp*=10; } } if (dis[b]==-1) printf("Impossible\n"); else printf("%d\n",dis[b]); }}
0 0
- 【poj 3126】Prime Path 题意&题解&代码(C++)
- 【POJ 3764】The xor-longest Path 中文题意&题解&代码(C++)
- 【hdu 5636】Shortest Path 中文题意&题解&代码(C++)
- POJ 2828 Buy Tickets 题意&题解&代码(c++)
- 【POJ 2104】K-th Number 题意&题解&代码(c++)
- 【POJ 1451】T9 中文题意&题解&代码(c++)
- 【POJ 3461】Oulipo 中文题意&题解&代码(C++)
- 【POJ 3630】Phone List 中文题意&题解&代码(C++)
- 【POJ 2296】 Ring 中文题意&题解&代码(C++)
- 【POJ 2778】DNA Sequence 中文题意&题解&代码(C++)
- 【poj 1321】 棋盘问题 题解&题意&代码(C++)
- 【poj 3009】Curling 2.0 中文题意&题解&代码(C++)
- 【poj 1426】Find The Multiple 题意&题解&代码(C++)
- 【poj 2251】 Dungeon Master 题意&题解&代码(C++)
- 【poj 3087】 Shuffle'm Up 题意&题解&代码(C++)
- 【poj 3414】Pots 题意&题解&代码(C++)
- 【poj 3278】Catch That Cow 题意&题解&代码(C++)
- 【poj 2531】Network Saboteur 题意&题解&代码(C++)
- cookie 和session 的区别详
- Qt 图像类 QImage QPixmap QBitmap QPicture 之区别与用途
- HTTP权威指南学习笔记:连接管理
- Java for循环的几种写法
- iOS 截取字符串中汉字 —— HERO博客
- 【poj 3126】Prime Path 题意&题解&代码(C++)
- C++11新特性学习笔记
- 我说《古炉》之狗尿苔
- lightoj-1223-Testing Mailboxes 区间dp
- 公钥密码学、数字签名与数字证书
- 轻松撰写功能规格书
- Android开发艺术探索读书笔记(二)
- 记嵌入式硬件开发实习——altium designer的使用
- LightOJ 1231 Coin Change (I)(部分背包)