#include <iostream>
#include <memory.h>
#include <queue>
using namespace std;
const int MAX = 100000;//竟然RE了三次,就是因为这里的MAX开小了!
int step[MAX];
bool prime[MAX];
int base[4] = {1, 10, 100, 1000};
int main()
{
int i, j, tc, num1, num2, n[5], newnum, oldnum, tmp;
//先将素数表打出来
for (i = 0; i < MAX; i++)
prime[i] = true;
for (i = 2; i < MAX; i++){
if (prime[i]){
for (j = 2; j * i < MAX; j++){
prime[i*j] = false;
}
}
}
//用bfs进行搜索与检测!
cin >> tc;
while (tc--){
cin >> num1 >> num2;
memset(step, 0, sizeof(step));
queue<int> p;
p.push(num1);
step[num1] = 1;
while (!p.empty()){
oldnum = p.front();
if (oldnum == num2) break;
p.pop();
tmp = oldnum;
n[1] = tmp % 10;
tmp /= 10;
n[2] = tmp % 10;
tmp /= 10;
n[3] = tmp % 10;
tmp /= 10;
n[4] = tmp % 10;
//cout << n[1] << " " << n[2] << " " << n[3] << " " << n[4] << endl;
for (i = 0; i < 10; i++){
newnum = oldnum - n[4] * 1000 + i * 1000;
if (i != 0 && prime[newnum] && !step[newnum]){
step[newnum] = step[oldnum] + 1;
p.push(newnum);
}
for (j = 1; j < 4; j++){
newnum = oldnum - n[j] * base[j-1] + i * base[j-1];
if (prime[newnum] && !step[newnum]){
step[newnum] = step[oldnum] + 1;
p.push(newnum);
}
}
}
}
cout << step[num2] - 1 << endl;
}
system("pause");
}
poj 3126 Prime Path
最新推荐文章于 2024-04-28 09:08:54 发布