POJ 3126 BFS
来源:互联网 发布:如何提高网店销量 知乎 编辑:程序博客网 时间:2024/04/30 01:30
题目链接:
POJ 3126 Prime Path
题目描述:
第一行:n
第二到n+1行:两个四位素数,求从第一个数变为第二个数所需的最小步数,每步可将第一个数的一个位(共四位)变为另一个数,且新得到的四位数也为一个素数。
Sample Input
3
1033 8179
1373 8017
1033 1033
Sample Output
6
7
0
思路:
求最短路径问题,bfs,先将1000~10000间素数打表。
伪代码:
//取队首for(每一位): for(0~9): if(是素数 && 之前没出现过) //入队,访问,步数+1; if(变化后与终点相等) return //步数
完整代码:
/************************************************************************* > File Name: poj_3126.cpp > Author: > Mail: > Created Time: ************************************************************************/#include<iostream>#include<stdio.h>#include<cstring>#include<cstdlib>#include<algorithm>#include<queue>#define LL long longusing namespace std;const int N = 10000;int n;bool prim[10009];int ans = 0;bool check(int k){ if(k == 0 || k == 1) return 0; if(k == 3 || k == 2) return 1; for(int i = 2; i*i <= k; i++) { if(k % i == 0) return 0; } return 1;}void init(){ for(int i = 1000; i < N; i++) { if(check(i)) prim[i] = 1; else prim[i] = 0; }}int bfs(int first, int last){ queue<int > q; bool v[N]; int t[5]; int dis[N]; memset(dis, 0, sizeof(dis)); memset(t, 0, sizeof(t)); memset(v, 0, sizeof(v)); v[first] = 1; q.push(first); while(!q.empty()) { int x = q.front(); if(x == last) return dis[x]; q.pop(); t[0] = x / 1000; t[1] = x % 1000 / 100; t[2] = x % 100 / 10; t[3] = x % 10; for(int i = 0; i <= 3; i++) { int k = t[i]; for(int j = 0; j <= 9; j++) { if(j != t[i]) { t[i] = j; int a = 1000*t[0]+100*t[1]+10*t[2]+t[3]; if(!v[a] && prim[a]) { q.push(a); dis[a] = dis[x]+1; v[a] = 1; } if(a == last) return dis[a]; } } t[i] = k; } } return -1;}int main(){ init(); scanf("%d", &n); int a, b; for(int i = 0; i < n; i++) { scanf("%d%d", &a, &b); int ans = bfs(a, b); if(ans != -1) printf("%d\n", ans); else printf("Impossible\n"); } return 0;}
0 0
- poj 3126 简单bfs
- poj 3126(BFS)
- poj 3126 bfs
- POJ 3126 BFS
- poj 3126 bfs
- POJ 3126--BFS
- poj 3126 BFS
- poj 3126 强行BFS
- POJ 3126 (BFS)
- POJ 3126 BFS
- 图论 BFS POJ 3126
- [BFS] POJ 3126
- POJ 3126 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 Prime Path(bfs)
- Xcode里-ObjC, -all_load, -force_load
- iOS推送 之 本地通知UILocalNotification
- LeetCode 331. Verify Preorder Serialization of a Binary Tree
- java中深拷贝和浅拷贝区别
- MATLAB-Direct access of structure fields returned by a function call is not allowed 的解决方法~
- POJ 3126 BFS
- windows下删除文件提示需要TrustedInstaller的解决办法
- ElasticSearch学习12_ES插件安装方法_离线安装和联网安装
- oracle提示“ORA-01002: 提取违反顺序”
- AR—如何在Unity中使用UserDefineTarget
- MAC上如何进入系统隐藏的目录
- PAT 乙级 1023. 组个最小数
- Struts-default.xml中拦截器个数
- iOS TableView 自带可拖动重排功能