poj 3126 Prime Path
来源:互联网 发布:h5工具是什么软件 编辑:程序博客网 时间:2024/06/05 04:28
点击打开链接
题意:一个四位素数,变到另一个四位的素数,每次只能改变四位数中的某一个,过程中的书必须都是素数。
问最少步数。
题解:
最少步数,明显的bfs。
素数打表。
开个4维标记。
爆搜就可。
#include<cstdio>#include<cstring>#include<iostream>#include<queue>#define LL long long#define ull unsigned long longusing namespace std;int f[11][11][11][11];int pre[10010];char n1[5],n2[5];struct node{ int a[5]; int step;};int judge(int a,int b,int c,int d){ int res=a*1000+b*100+c*10+d; if(a==n2[0]-'0'&&b==n2[1]-'0'&&c==n2[2]-'0'&&d==n2[3]-'0'){ return 2; } if(f[a][b][c][d]) return 0; if(!pre[res]) return 1; return 0;}int bfs(int a,int b,int c,int d){ node u,v; u.a[0]=a,u.a[1]=b,u.a[2]=c,u.a[3]=d,u.step=0; int s=judge(a,b,c,d); if(s==2) return 0; f[a][b][c][d]=1; queue<node> que; que.push(u); while(!que.empty()){ v=que.front(); que.pop(); for(int i=0;i<4;i++){ for(int j=0;j<10;j++){ if(i==0&&j==0) continue; u=v;u.a[i]=j;u.step=v.step+1; if(judge(u.a[0],u.a[1],u.a[2],u.a[3])==2) return u.step; else if(judge(u.a[0],u.a[1],u.a[2],u.a[3])==1){ f[u.a[0]][u.a[1]][u.a[2]][u.a[3]]=1; que.push(u); //printf("%d %d %d %d %d\n",u.a[0],u.a[1],u.a[2],u.a[3],u.step); } } } } return -1;}int main(){ int T; pre[0]=pre[1]=1; for(int i=2;i<=10010;++i){ if(!pre[i]){ for(int j=i+i;j<=10010;j+=i) pre[j]=1; } } scanf("%d",&T); while(T--){ memset(f,0,sizeof(f)); scanf("%s %s",n1,n2); int ans=bfs(n1[0]-'0',n1[1]-'0',n1[2]-'0',n1[3]-'0'); if(ans==-1) printf("Impossible\n"); else printf("%d\n",ans); } return 0;}
0 0
- POJ 3126 Prime Path
- POJ 3126 Prime Path
- poj 3126Prime Path
- POJ -3126-Prime Path
- POJ 3126 Prime Path
- poj 3126 Prime Path
- POJ 3126 - Prime Path
- POJ 3126 Prime Path
- poj 3126 prime path
- POJ 3126 Prime Path
- Prime Path poj 3126
- POJ 3126 Prime Path
- poj 3126 Prime Path
- POJ 3126 Prime Path
- poj 3126 Prime path
- poj - 3126 - Prime Path
- POJ 3126 Prime Path
- POJ 3126 Prime Path
- Java网页数据采集器[上篇-数据采集]
- Vue学习笔记(3)关于Vue的计算属性
- spring(基础18) Sprin事务和synchronized锁的一些问题
- Leetcode 389. Find the Difference
- Java基础之在return中使用finally
- poj 3126 Prime Path
- Java网页数据采集器[中篇-数据存储]
- 使用Fiddler进行iOS APP的HTTP/HTTPS抓包
- com.google.android.gts.placement.CoreGmsAppsTest#testCoreGmsAppsPreloaded fail
- ThinkPHP读写Memcached
- leetcode118
- Java网页数据采集器[下篇-数据查询]
- Junit测试
- BaseAdapter的最简单的封装