您的位置:首页 > 其它

POJ 3126 - Prime Path(BFS)

2015-02-23 17:23 316 查看
题目:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  POJ