Prime Path POJ - 3126
https://vjudge.net/problem/POJ-3126
题意:
给一个四位数n,每次可以改变一位数,而且改变后的这个数必须是四位的素数,求最少改变几次可以变到m。
Sample Input
3
1033 8179
1373 8017
1033 1033
Sample Output
6
7
0
样例一:
1033
1733
3733
3739
3779
8779
8179
思路:
BFS。 可以先处理四位以内的素数。广搜每一位都变成0~9。
Code:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
const int N = 10005;
struct node {
int x, step;
node(int x = 0, int step = 0): x(x), step(step) {}
};
int p[N];
bool book[N];
bool vis[N];
int cnt = 0;
void prime() {
cnt = 0;
for (int i = 2; i < N; i++) {
if (book[i] == 0) p[++cnt] = i;
for (int j = 1; j <= cnt && i * p[j] <= N; j++) {
book[i * p[j]] = 1;
if (i % p[j] == 0) break;
}
}
}
int bfs(int x, int y) {
memset(vis, 0, sizeof(vis));
queue<node>q;
node no = node(x, 0);
q.push(no);
vis[x] = 1;
while (!q.empty()) {
node now = q.front();
q.pop();
if (now.x == y)return now.step;
now.step++;
int k = now.x, t = 1000;
for (int i = 1; i <= 4; i++) {
int kn = k - k % (t * 10) / t * t; //kn表示k的第i为置0
for (int j = 0; j <= 9; j++) {
now.x = kn + j * t; //第i位变成0~9的情况
if (now.x > 1000 && !vis[now.x] && book[now.x] == 0) {
vis[now.x] = 1;
q.push(now);
}
}
t /= 10;
}
}
return -1;
}
int main() {
prime(); //处理素数
int T, x, y, ans;
scanf("%d", &T);
while (T--) {
scanf("%d%d", &x, &y);
ans = bfs(x, y);
if (ans != -1)
printf("%d\n", ans);
else
printf("Impossible\n");
}
return 0;
}