toj2648-Prime Path解题报告
- 我只是想玩一下这个新粗来的编辑器,终于等来了,^_^哈哈~…
Prime Path
给两个数a和b,每次操作仅可以改变一位数,并且中间数只能是质数,问经过多少步可以从a变到b.
思路:BFS简单搜索一下即可.
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct node {
int a;
int step;
bool operator==(const node& b)const {
return b.a == a;
}
} otst, dest;
const int MAX = 10007;
bool vis[MAX];
bool isPrime[MAX];
int eNext[5] = {1, 10, 100, 1000, 10000};
int BFS() {
memset(vis, false, sizeof(vis));
vis[otst.a] = true;
queue<node> Q;
Q.push(otst);
while (!Q.empty()) {
node now = Q.front(), next;
Q.pop();
if (now == dest) {
return now.step;
}
int num[4], tmp = now.a;
for (int i = 0; i < 4; ++i) {
num[i] = tmp % 10;
tmp /= 10;
}
next.step = now.step + 1;
for (int i = 0; i < 4; ++i) {
for (int j = 1; j < 10; ++j) {
int mNext[4];
memcpy(mNext, num, sizeof(num));
mNext[i] = (num[i] + j) % 10;
tmp = 0;
for (int i = 3; i >= 0; --i) {
tmp *= 10;
tmp += mNext[i];
}
if (tmp > 999 && isPrime[tmp] && !vis[tmp]) {
vis[tmp] = true;
next.a = tmp;
Q.push(next);
}
}
}//for
}//while
return -1;
}
int main() {
memset(isPrime, true, sizeof(isPrime));
for (int i = 2; i < MAX / i; ++i) {
for (int j = i * i; j < MAX; j += i) {
isPrime[j] = false;
}
}
int T, a, b;
scanf(" %d", &T);
while (T--) {
scanf(" %d %d", &a, &b);
otst.a = a, otst.step = 0;
dest.a = b;
int ans = BFS();
if (ans == -1) {
puts("Impossible");
} else {
printf("%d\n", ans);
}
}
return 0;
}
- 试用了一下,
- 还是很棒的!!!
- 有木有?!!
- 还是很棒的!!!