POJ 3126 primepath bfs

时间:2024-04-08 16:34:20

题目链接:http://poj.org/problem?id=3126

题意:1维的坐标轴,给出起点和终点,求从起点到终点变换经历的最短的步数。起点,终点和中间变换的数字都是4位,而且都是质数。

思路:普通的广搜、精神状态不佳、找了许久的bug。后来发现是prime函数和pow函数都很丧心病狂的写错了、

附 AC 代码:

 // T_T 电脑突然重启什么都没有了。。没有了、
//大概4*9入口的广搜。 从初始点开始 对于每个扩展点加入队列 知道找到ed、或者尝试完所有可能的情况、 #include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
#include <math.h>
#define maxn 100000
#include <queue>
int st, ed;
bool vis[];
int step[]; int val1[] = {, , , , , , , , , };
int val2[] = {, , , , , , , , , };
int val3[] = {, , , , , , , , , };
int val4[] = {, , , , , , , , }; queue<int>que; bool prime(int n) {
for (int i=; i<=sqrt(n); ++i) {
if (n%i == )
return false;
}
return true;
} int pow(int a, int b) {
if (b == ) return ;
for (int i=; i<b; ++i) {
a *= ;
}
return a;
} void dfs() {
memset(vis, , sizeof(vis));
for (int i=; i<; ++i) {
step[i] = maxn;
}
while(!que.empty())
que.pop();
que.push(st);
step[st] = ;
vis[st] = ; while(!que.empty()) {
int now = que.front();
que.pop();
if (now == ed) {
return;
} int temp = now;
int val[];
int cnt = ;
while (temp) {
val[cnt] = temp % ;
temp /= ;
val[cnt] *= pow(, cnt);
cnt++;
} temp = now;
temp -= val[];
for (int i=; i<; ++i) {
temp += val1[i];
if (!vis[temp] && temp % && temp <= ed) {
if (prime(temp)) {
step[temp] = step[now] + ;
vis[temp] = ;
que.push(temp);
}
}
temp -= val1[i];
} temp = now;
temp -= val[];
for (int i=; i<; ++i) {
temp += val2[i];
if (!vis[temp] && temp % ) {
if (prime(temp)) {
step[temp] = step[now] + ;
vis[temp] = ;
que.push(temp);
}
}
temp -= val2[i];
} temp = now;
temp -= val[];
for (int i=; i<; ++i) {
temp += val3[i];
if (!vis[temp] && temp % ) {
if (prime(temp)) {
step[temp] = step[now] + ;
vis[temp] = ;
que.push(temp);
}
}
temp -= val3[i];
} temp = now;
temp -= val[]; for (int i=; i<; ++i) {
temp += val4[i];
if (!vis[temp] && temp % ) {
if (prime(temp)) {
step[temp] = step[now] + ;
vis[temp] = ;
que.push(temp);
}
}
temp -= val4[i];
}
}
return;
} int main() {
int t;
cin >> t;
while(t--) {
cin >> st >> ed;
dfs();
int ans = step[ed];
if (ans == maxn) {
cout << "Impossible\n";
}
else cout << ans << endl;
}
return ;
}