bfs--POJ 3126 Prime Path
2016-08-13 20:17
477 查看
思路: 搜索位上的数字 可以构成素数
#include <iostream> #include <stdio.h> #include <queue> #include <cstring> using namespace std; int n, m; int prime[10000]; void init() { int i,j; for( i=1000;i<=9999;i++) { for(j=2;j<=i/2;j++) if(i%j==0) break; if(j==i/2+1) prime[i]=1; } } const int N = 10010; int vis ; struct node { int x, step; }; queue<node > Q; void bfs() { int x,stp,i; while(!Q.empty()) { node tmp; tmp=Q.front(); Q.pop(); x=tmp.x; stp=tmp.step; if(x==m) { printf("%d\n",stp); return ; } for(int i=1;i<=9;i+=2) { int tep=x/10*10+i; if((!vis[tep])&&(tep!=x)&&(prime[tep])) { vis[tep]=1; node temp; temp.x=tep; temp.step=stp+1; Q.push(temp); } } for(int i=0;i<=9;i++) { int tep=x/100*100+i*10+x%10; if(!vis[tep]&&tep!=x&&prime[tep]) { vis[tep]=1; node temp; temp.x=tep; temp.step=stp+1; Q.push(temp); } } for(int i=0;i<=9;i++) { int tep=x/1000*1000+i*100+x%100; if(!vis[tep]&&tep!=x&&prime[tep]) { vis[tep]=1; node temp; temp.x=tep; temp.step=stp+1; Q.push(temp); } } for(int i=1;i<=9;i++) { int tep=i*1000+x%1000; if(!vis[tep]&&tep!=x&&prime[tep]) { vis[tep]=1; node temp; temp.x=tep; temp.step=stp+1; Q.push(temp); } } } printf("Impossible\n"); return ; } int main() { int t; cin>>t; init(); while(t--) { while(!Q.empty()) Q.pop(); memset(vis,0,sizeof(vis)); cin>>n>>m; vis =1; node tmp; tmp.x=n; tmp.step=0; Q.push(tmp); bfs(); } return 0; }
相关文章推荐
- POJ 3126 Prime Path(素数打表+bfs)
- POJ - 3126 Prime Path(15.10.10 搜索专题)bfs
- POJ 3126 Prime Path 第一道BFS 循环队列,AC的很辛苦!
- (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 (BFS)
- Prime Path POJ - 3126 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 循环队列,AC的很辛苦!
- poj 3126 Prime Path (bfs)
- POJ 3126 Prime Path bfs求最短路
- Prime Path - POJ 3126 BFS宽度(广度)优先搜索
- poj 3126 Prime Path (bfs)
- poj 3126 Prime Path(bfs)
- POJ-3126 Prime Path ( BFS )