Prime Path POJ
来源:互联网 发布:app软件开发教程 编辑:程序博客网 时间:2024/06/05 06:29
Prime Path
POJ - 3126比较基础的BFS思想,因为只有四位数,所以把每一位都当做入口,枚举所有可能的数字,遇到符合的就进入队列。
#include<iostream>#include <cstdio>#include <string>#include <cstring>#include <algorithm>#include <queue>#include <cmath>using namespace std;int t[10];int n;int prime[10005];int v[10005];int vis[10000];int from,to;int time;void get_prime(){ int x=sqrt(10005)+1; for(int i=2; i<=10005; i++) { if(!prime[i]) {// cout << i << endl; for(int j=i*2; j<10005; j+=i) {// cout << j <<endl; prime[j]=1; } }// cout<< "2"; } prime[0]=prime[1]=prime[2]=1;}int bfs(){ queue<int>que;// que.clear(); que.push(from); while(!que.empty()) { int now=que.front(); que.pop(); t[0]=now/1000; t[1]=(now/100)%10; t[2]=(now/10)%10; t[3]=(now%10); if(now==to) return vis[now];// printf("%d %d %d %d %d\n",now,t[0],t[1],t[2],t[3]); for(int i=0; i<4; i++) { for(int j=0; j<10; j++) { int v; if(i==0) v=j*1000+t[1]*100+t[2]*10+t[3]; else if(i==1) v=t[0]*1000+j*100+t[2]*10+t[3]; else if(i==2)v=t[0]*1000+t[1]*100+j*10+t[3]; else if(i==3)v=t[0]*1000+t[1]*100+t[2]*10+j;// cout << v << '*' <<endl; if(v!=now&& !prime[v]&&!vis[v]&&v>=1000&&v<=9999) { vis[v]=vis[now]+1; if(v==to) {// cout << "*************"<<endl; return vis[now]+1; } que.push(v);// cout << "push:" << v <<endl; } } } } return -1;}int main(){ get_prime(); scanf("%d",&n); while(n--) { memset(vis,0,sizeof(vis)); scanf("%d%d",&from,&to); time=bfs(); if(time!=-1) cout << time <<endl; else cout << "Impossible\n" ; } 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
- Enum问题总结
- 队列初体验
- Dropout: A Simple Way to Prevent Neural Networks from Overfitting
- numa,numa node 和物理内存
- Centos下搭建LNMP(Linux+MySQL+nginx+PHP)
- Prime Path POJ
- 点击按钮出现5秒倒计时js代码
- Android主题换肤
- subString 截取字符串
- git提交本地文件到码云
- Linux 下 seq 命令用法
- DP——HDU 4571
- 1602滚动显示
- win 7与Ubuntu 14.04双系统安装