poj 3126 Prime Path( bfs + 素数)
2013-08-26 20:03
423 查看
题目:http://poj.org/problem?id=3126
题意:给定两个四位数,求从前一个数变到后一个数最少需要几步,改变的原则是每次只能改变某一位上的一个数,而且每次改变得到的必须是一个素数;
题意:给定两个四位数,求从前一个数变到后一个数最少需要几步,改变的原则是每次只能改变某一位上的一个数,而且每次改变得到的必须是一个素数;
#include <iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<stack> #include<queue> #include<iomanip> #include<cmath> #include<map> #include<vector> #include<algorithm> using namespace std; int p[10010],vis[10010]; int a,b,t; struct node { int a,step; }pos,next; void prime() //快速求素数的模板 { int i,j; memset(p,-1,sizeof(p)); p[0]=p[1]=0; for(i=3; i<10005; i++) { if(i%2==0) p[i]=0; if(p[i]) for(j=i*2; j<10005; j+=i) p[j]=0; } } int change(int x,int i,int j) //i代表改变哪一位(个十百千),j代表改变为几,x是原数 { if(i==1) return (x/10)*10+j; else if(i==2) return (x/100)*100+x%10+j*10; else if(i==3) return (x/1000)*1000+x%100+j*100; else if(i==4) return (x%1000)+j*1000; return 0; } void bfs() { int i,j; queue<node>q; next.a=a; next.step=0; vis[a]=1; q.push(next); while(!q.empty()) { pos=q.front(); q.pop(); next.step=pos.step+1; for(i=1; i<=4; i++) for(j=0; j<10; j++) { if(i==4&&j==0) continue; next.a=change(pos.a,i,j); if(next.a==b) { cout<<next.step<<endl; return; } if(p[next.a]&&!vis[next.a]) { q.push(next); vis[next.a]=1; } } } cout<<"Impossible"<<endl; } int main() { prime(); cin>>t; while(t--) { memset(vis,0,sizeof(vis)); cin>>a>>b; if(a==b) { cout<<"0"<<endl; continue; } bfs(); } return 0; }
相关文章推荐
- POJ 3126 Prime Path(BFS + 素数打表)
- POJ 3126 Prime Path (素数+BFS)
- POJ 3126 Prime Path(素数打表+BFS)
- POJ 3126 Prime Path(素数变换路径)
- 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-素数变换一位)
- POJ 3126 Prime Path(素数,BFS最短路)
- poj 3126 Prime Path (线性素数筛 + bfs)
- (BFS11.1.1)POJ 3126 Prime Path(计算从初始素数到目标素数的最短路径长度)
- POJ - 3126 Prime Path (素数表+BFS)
- POJ 3126 Prime Path 素数筛,bfs
- Poj 3126 Prime Path (BFS 素数打表)
- 【POJ】3126 - Prime Path 素数
- CD0J/POJ 851/3126 方老师与素数/Prime Path BFS
- POJ训练计划3126_Prime Path(素数+BFS)
- poj 3126 Prime Path([kuangbin带你飞]专题一 简单搜索)