POJ 3126-Prime Path(BFS)
2017-06-23 19:26
393 查看
题目地址:POJ 3126
题意:给你两个4位的都是素数正整数n,m,每次能够变 个十百千位 中的一个数(变化后也是素数,问最少经过多少次变化n能变成m,假设不能输出Impossible(窝认为并没有不成立的情况
思路:每次变化一位,然后搜就好了。
题意:给你两个4位的都是素数正整数n,m,每次能够变 个十百千位 中的一个数(变化后也是素数,问最少经过多少次变化n能变成m,假设不能输出Impossible(窝认为并没有不成立的情况
思路:每次变化一位,然后搜就好了。
#include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <iostream> #include <sstream> #include <algorithm> #include <set> #include <queue> #include <stack> #include <map> #pragma comment(linker, "/STACK:102400000,102400000") using namespace std; typedef __int64 LL; const int inf=0x3f3f3f3f; const double pi= acos(-1.0); const double esp=1e-7; const int Maxn=1e6+10; struct node { int x1,x2,x3,x4; int cnt; }q[Maxn],f1,f2; int n,m; int vis[Maxn]; int isprime(int x) { for(int i=2;i<=sqrt(x);i++) if(x%i==0) return 0; return 1; } void BFS() { memset(vis,0,sizeof(vis)); queue<node >q; f1.x1=n%10,n/=10; f1.x2=n%10,n/=10; f1.x3=n%10,n/=10; f1.x4=n; f1.cnt=0; vis =1; q.push(f1); while(!q.empty()){ f1=q.front(); q.pop(); if(f1.x4*1000+f1.x3*100+f1.x2*10+f1.x1==m){ printf("%d\n",f1.cnt); return ; } for(int i=1;i<=9;i++){ if(i!=f1.x4){ int tmp=i*1000+f1.x3*100+f1.x2*10+f1.x1; if(isprime(tmp)&&!vis[tmp]){ vis[tmp]=1; f2.x4=i; f2.x3=f1.x3; f2.x2=f1.x2; f2.x1=f1.x1; f2.cnt=f1.cnt+1; q.push(f2); } } } for(int i=0;i<=9;i++){ if(i!=f1.x3){ int tmp=f1.x4*1000+i*100+f1.x2*10+f1.x1; if(isprime(tmp)&&!vis[tmp]){ vis[tmp]=1; f2.x4=f1.x4; f2.x3=i; f2.x2=f1.x2; f2.x1=f1.x1; f2.cnt=f1.cnt+1; q.push(f2); } } } for(int i=0;i<=9;i++){ if(i!=f1.x2){ int tmp=f1.x4*1000+f1.x3*100+i*10+f1.x1; if(isprime(tmp)&&!vis[tmp]){ vis[tmp]=1; f2.x4=f1.x4; f2.x3=f1.x3; f2.x2=i; f2.x1=f1.x1; f2.cnt=f1.cnt+1; q.push(f2); } } } for(int i=0;i<=9;i++){ if(i!=f1.x3){ int tmp=f1.x4*1000+f1.x3*100+f1.x2*10+i; if(isprime(tmp)&&!vis[tmp]){ vis[tmp]=1; f2.x4=f1.x4; f2.x3=f1.x3; f2.x2=f1.x2; f2.x1=i; f2.cnt=f1.cnt+1; q.push(f2); } } } } puts("Impossible"); return ; } int main() { int T; scanf("%d",&T); while(T--){ scanf("%d %d",&n,&m); BFS(); } return 0; }
相关文章推荐
- 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 / Northwestern Europe 2006 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 && Sicily 1444 Prime Path (BFS广度优先搜索)
- POJ-3126-Prime Path【BFS】
- CD0J/POJ 851/3126 方老师与素数/Prime Path BFS
- Prime Path(POJ 3126 BFS)
- POJ 3126 Prime Path(BFS)
- POJ-3126--Prime Path---BFS广搜