POJ3126-Prime Path
来源:互联网 发布:java string转time 编辑:程序博客网 时间:2024/05/16 19:39
题目链接:POJ3126
思路,先打一个素数表,然后BFS的时候,把4位数每一位单独考虑,看看4位数是否为质数,是的话就加入队列。
AC代码:
#include<stdio.h>#include<string.h>#include<queue>using namespace std;const int maxn=10005;bool f[maxn];bool vis[maxn];int n,d1,d2,d3,d4,res;struct node{ int num; int step;};void tb(){//false is prime memset(f,false,sizeof(f)); f[0]=true; f[1]=true; f[2]=false; for(int i=2;i<maxn;i++){ if(f[i]) continue; else{ for(int j=i+i;j<maxn;j+=i){ f[j]=true; } } }}void getnum(int n){ d1=n%10; d2=(n%100)/10; d3=(n%1000)/100; d4=n/1000;}bool bfs(int s,int e){ memset(vis,false,sizeof(vis)); queue<node> q; node t1,t2,t3; t1.num=s; t1.step=0; q.push(t1); vis[s]=true; while(!q.empty()){ t2=q.front(); q.pop(); //printf("%d\n",t2.num); if(t2.num==e){ res=t2.step; return true; } getnum(t2.num); //d4 for(int i=1;i<=9;i++){ if(i!=d4){ int tmp=i*1000+d3*100+d2*10+d1; if(!f[tmp]&&!vis[tmp]){ t3.num=tmp; t3.step=t2.step+1; vis[tmp]=true; q.push(t3); } } } //d3 for(int i=0;i<=9;i++){ if(i!=d3){ int tmp=d4*1000+i*100+d2*10+d1; if(!f[tmp]&&!vis[tmp]){ t3.num=tmp; t3.step=t2.step+1; vis[tmp]=true; q.push(t3); } } } //d2 for(int i=0;i<=9;i++){ if(i!=d2){ int tmp=d4*1000+d3*100+i*10+d1; if(!f[tmp]&&!vis[tmp]){ t3.num=tmp; t3.step=t2.step+1; vis[tmp]=true; q.push(t3); } } } //d1 for(int i=0;i<=9;i++){ if(i!=d1){ int tmp=d4*1000+d3*100+d2*10+i; if(!f[tmp]&&!vis[tmp]){ t3.num=tmp; t3.step=t2.step+1; vis[tmp]=true; q.push(t3); } } } } return false;}int main(){ tb(); scanf("%d",&n); for(int i=0;i<n;i++){ int a,b; scanf("%d%d",&a,&b); // getnum(a); // printf("%d%d%d%d\n",d4,d3,d2,d1); // getnum(b); // printf("%d%d%d%d\n",d4,d3,d2,d1); if(bfs(a,b)) printf("%d\n",res); else printf("Impossible\n"); } 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
- [bzoj3438][网络流]小M的作物
- Ansible介绍
- SpringBoot定时任务(@Scheduled)说明
- 主成分分析(PCA)
- Cordova打包Vue项目
- POJ3126-Prime Path
- seo人不仅仅需要懂技术还需要懂产品与运营
- 高级纹理查询函数
- 关于使用js设置值的问题
- JS获取当前完整的url地址以及参数的方法
- 音视频同步(播放)原理
- 基于.NET平台常用的框架整理
- mysql中的文件路径书写
- 将windows socket 初始化接口封装成一个类,方便好用