POJ 3126 - Prime Path(BFS)
来源:互联网 发布:淘宝卖家注册子账号 编辑:程序博客网 时间:2024/06/11 07:44
题目:
http://poj.org/problem?id=3126
思路:
BFS,从队列中取出一个数,改变其中的一位,将符合条件的数字再存入队列中,直到找到b为止。
CODE:
#include <iostream>#include <cstdio>#include <cstring>#include <queue>using namespace std;const int maxn = 10005;bool vis[maxn], v[maxn];int k;int ans, a, b;int step[maxn], na[5];queue<int> que;void prime(){ k = 0; memset(vis, 0, sizeof(vis)); for(int i = 2; i < maxn; ++i) { if(vis[i]) continue; for(int j = i+i; j < maxn; j+=i) vis[j] = 1; }}void chg(int a){ int k = 0; while(a > 0) { na[k++] = a % 10; a /= 10; }}void bfs(){ memset(step, 0, sizeof(step)); memset(v, 0, sizeof(v)); que.push(a); v[a] = 1; while(que.size()) { int now = que.front(); que.pop(); if(now == b) { printf("%d\n", step[b]); while(que.size()) que.pop(); return; } int num; chg(now); for(int i = 0; i < 4; ++i) { int tmp = na[i]; na[i]++; for(int j = 0; j < 10; ++j) { if(i == 3 && j == 0) continue; na[i] = j; num = na[0] + na[1]*10 + na[2]*100 + na[3]*1000; if(!vis[num] && !v[num]) { step[num] = step[now] + 1; v[num] = 1; que.push(num); } na[i]++; } na[i] = tmp; } }}int main(){//freopen("in", "r", stdin); prime(); int T; scanf("%d", &T); while(T--) { scanf("%d %d", &a, &b); if(a == b) { printf("0\n"); continue; } ans = 0; if(a > b) { int t = a; a = b; b = t; } bfs(); } return 0;}
0 0
- poj 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算法)
- Prime Path (poj 3126 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、埃氏筛法)
- 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)
- 王垠的「40 行代码」真如他说的那么厉害吗?
- C#设计模式(十五)状态者模式
- 用 excel 將一般日期轉成 unix timestamp
- UVa 11136 - Hoax or what
- 定义属性时,什么情况使用copy、assign、retain?
- POJ 3126 - Prime Path(BFS)
- 在C#中利用Keep-Alive处理Socket网络异常断开的方法
- PowerMockito的基本使用记录
- Android开发之如何保证Service不被杀掉(broadcast+system/app)
- Sublime Text 2
- 对象是什么时候被release的?
- Webbrowser控件史上最强技巧全集
- 【知乎】出身富贵人家到底有什么地方值得人向往?
- action 植栈