POJ3126--- Prime Path
来源:互联网 发布:开淘宝怎么拿货 编辑:程序博客网 时间:2024/05/25 21:36
从一个素数到另一个素数,每次只改变一个数,输出最小次数。
#include<stdio.h>#include<string.h>#include<algorithm>#include<math.h>#include<string>#include<iostream>#include<queue>using namespace std;bool prime[10000];void init(){ for(int i=1;i<10000;i++) prime[i]=true; for(int i=2;i<10000;i++){ int flag=0;double mark=sqrt(i); for(int j=2;j<=mark;j++) { if(i%j==0) {flag=1;break;} } if(flag) prime[i]=false; } for(int i=0;i<1000;i++) prime[i]=false;//前1000个数可能搜索到,但是不能进入搜索中}string a,b;bool vis[10000];void bfs(){ queue<pair<string,int> >q; while(!q.empty()) q.pop(); q.push(make_pair(a,0)); while(!q.empty()){ pair<string,int>now=q.front();q.pop(); if(now.first==b){ cout<<now.second<<endl; return ; }//先看看第一个和最后一个是不是相同的 for(int i=0;i<10;i++){ for(int j=0;j<4;j++){//对四个字符进行40个搜索 string tmp=now.first; tmp[j]=i+'0'; int num = (tmp[0]-'0')*1000+(tmp[1]-'0')*100+(tmp[2]-'0')*10+tmp[3]-'0'; if(!vis[num]&&prime[num]){ vis[num]=true; q.push(make_pair(tmp,now.second+1)); } if(tmp==b){//搜到了拉倒 cout<<now.second+1<<endl; return ; } } } }}int main(){ int t; init(); cin>>t; for(int kk=1;kk<=t;kk++){ cin>>a>>b; memset(vis,0,sizeof vis); bfs(); } return 0;}
0 0
- poj3126 - Prime Path
- hdu1973 || poj3126 Prime Path
- POJ3126 Prime Path
- POJ3126--Prime Path
- POJ3126 Prime Path
- [POJ3126]Prime Path+BFS
- POJ3126 Prime Path 素数
- Prime Path(poj3126)
- poj3126 Prime Path
- POJ3126--- Prime Path
- POJ3126 Prime Path(bfs)
- POJ3126 Prime Path(BFS)
- POJ3126 - Prime Path
- POJ3126-Prime Path
- poj3126 Prime Path
- poj3126 prime path
- POJ3126 Prime Path
- poj3126 prime path bfs
- 设计模式之 - 策略模式
- [Python]网络爬虫(七):Python中的正则表达式教程
- spinner自定义布局文件设置字体大小和颜色
- HDU_2074 叠筐
- maven处理依赖冲突(未完)
- POJ3126--- Prime Path
- [Python]网络爬虫(八):糗事百科的网络爬虫(v0.3)源码及解析(简化更新)
- STL标准
- 用link方式搭建eclipse + PyDev环境
- 人造矿泉水与天然矿泉水的区别
- webView 手势缩放以及自适应屏幕
- [Python]网络爬虫(九):百度贴吧的网络爬虫(v0.4)源码及解析
- eclipse里的svn不显示版本号或修改人、修改时间
- JAVA把字符串当作表达式运行