POJ 3126--BFS
来源:互联网 发布:北京语言大学网络继续 编辑:程序博客网 时间:2024/05/16 15:38
一道BFS题目
题意大致如下:
给定两个四位数 x ,y(x ,y都是素数)。要求从x变化到y。
变化规则为每次只能改变四位数x中的其中一位得到k,要求k也是素数。在这样的变化规则下求x变化到y的最小次数。
根据规则直接BFS就行。
代码如下:#include <stdio.h>#include <queue>#include <iostream>#include <cstring>#include <math.h>using namespace std;int m,n;int vis[10000];struct node{ int prime; int step;};int a[20000];int flag[20000];//给10000以内的所有素数打表void isPrime(){ memset (flag,0,sizeof(flag)); for(int i=2; i<10000; i++) { if(flag[i]) { continue ; } else { for(int j=i+i; j<10000; j+=i) { flag[j]=1; } } }}void bfs(){ queue <node> que; node x; x.prime=m; x.step=0; vis[x.prime]=1; que.push(x); while(!que.empty()) { node fx; fx=que.front(); que.pop(); if(fx.prime==n) { cout<<fx.step<<endl; break; } int po=1; for(int i=1; i<=4; i++) { po*=10; int k=fx.prime; int s=fx.prime%po; k=k-s+fx.prime%(po/10);//k为改变一位数之后的最小的数字,例如1033改变十位上的数字则k=1003,改变千位则k=33; for(int j=0; j<=9; j++) { if(i==4&&j==0)<span style="white-space:pre"></span>//千位进行特判 因为千位不能为0 所以直接从1000开始加。其他的从0开始 continue; int y=k+j*pow(10,i-1); if(y==fx.prime) continue; if(!vis[y]&&!flag[y]&&y<10000) { vis[y]=1; node fy; fy.prime=y; fy.step=fx.step+1; que.push(fy); } } } } return;}int main(){ int t; isPrime(); cin>>t; while(t--) { memset(vis,0,sizeof(vis)); cin>>m>>n; bfs(); } return 0;}
0 0
- poj 3126 简单bfs
- poj 3126(BFS)
- poj 3126 bfs
- POJ 3126 BFS
- poj 3126 bfs
- POJ 3126--BFS
- poj 3126 BFS
- poj 3126 强行BFS
- POJ 3126 (BFS)
- POJ 3126 BFS
- 图论 BFS POJ 3126
- [BFS] POJ 3126
- 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)
- A. Theatre Square
- poj 2728 Desert King(最优比率生成树)
- 前端框架对页面的损害+如何判断一个dom是否存在某个属性
- 二叉树的链式结构实现
- new和malloc的区别
- POJ 3126--BFS
- 各银行网上支付接口 开通流程及所需材料 中、农、建、工
- python实现ZOJ1745(简单模拟)
- Java线程池使用说明
- 黑马程序员---Objective-C 三大特性---继承
- Node.js入门系列——Express.js安装
- MIT算法导论——第六讲.Order statistics and Median
- UVALive 4015 - Caves(树形DP)
- [授权发表]基于 VNCServer + noVNC 构建 Docker 桌面系统