poj 3126 Prime Path
来源:互联网 发布:重庆华人数据恢复公司 编辑:程序博客网 时间:2024/05/03 07:54
问题描述:给定两个素数a b,求a变幻到b需要几步
并且变幻时只有一个数字不同,并且是素数
思路:我开始怎么都没想到用bfs 我只记得做过这个,看了别人的思路才想起来,一天不做,费3天.。把所有的素数打表,然后bfs深搜
#include <iostream>#include <stdio.h>#include <iomanip>#include <string.h>#include <map>#include <queue>using namespace std;bool prime[10001];void init(){ int i,j; for(i=1000;i<=10000;i++){ for(j=2;j<i;j++) if(i%j==0){ prime[i]=false; break; } if(j==i) prime[i]=true; }}int bfs(int a,int b){ bool vis[10001]; queue <int>q; int v,i,j,temp,vtemp,count[10001],t[4]; memset(vis,0,sizeof(vis)); memset(count,0,sizeof(count)); q.push(a); while(!q.empty()) { v=q.front(); if(v==b) return count[v]; q.pop(); vis[v]=1; t[0]=v%10; t[1]=v/10%10; t[2]=v/100%10; t[3]=v/1000; for(j=0; j<4; j++) { temp=t[j]; for(i=0; i<=9; i++) { t[j]=i; vtemp=t[3]*1000+t[2]*100+t[1]*10+t[0]; if(i!=temp) { if(prime[vtemp]&&vis[vtemp]==0) { count[vtemp]=count[v]+1; vis[vtemp]=true; q.push(vtemp); } } if(vtemp==b) return count[vtemp]; } t[j]=temp; } }return -1;}int main(){ int t; init(); scanf("%d",&t); while(t--) { int a,b; scanf("%d%d",&a,&b); int ans=bfs(a,b); 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
- makefile语法
- hdu:2032 杨辉三角
- MyEclipse2014 使用 hibernate3.jar 生成数据库实体类和xml map映射文件 (补16年12月)
- .9png
- springIoc创建对象之有参构造器
- poj 3126 Prime Path
- 百度百科:Java内部类
- TYVJ-P1005 01背包问题
- VTK修炼之道44:图形进阶_vtkPolyData数据源讨论与数据创建
- JDBC设置事务的隔离级别和转账案例
- Android环境配置
- GOlang中对flag.Prase()的疑问
- LeetCode 421 Maximum XOR of Two Numbers in an Array 解题报告
- DDMS出现:远程主机强迫关闭了一个现有的连接的解决办法