bfs水题,直接上代码。
/*************************************************************************
> File Name: poj\poj_3126.cpp
> Author: ljf_cnyali
> Mail: 2724424647@qq.com
> Last modifiedz: 2016-08-26 20:41
> Description: This is a large group of God's program information.
************************************************************************/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<ctime>
#include<algorithm>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
#define REP(i, a, b) for(int i = (a), _end_ = (b);i <= _end_; ++i)
const int maxn = 10000;
int f[maxn], vis[maxn];
struct node {
int x, s;
};
void INIT() {
REP(i, 1, 9999)
f[i] = 1;
REP(i, 2, 9999)
if(f[i])
for(int j = i * 2;j <= 9999; j += i)
f[j] = 0;
}
int x, y;
void BFS() {
if(x == y) {
printf("0\n");
return;
}
queue<node> q;
memset(vis, 0, sizeof(vis));
vis[x] = true;
q.push((node){x, 0});
while(!q.empty()) {
node p = q.front();
q.pop();
for(int i = 1;i <= 1000; i *= 10) {
REP(j, 0, 9) {
if(i == 1000 && j == 0)
continue;
int t = p.x % i + j * i + p.x / (i * 10) * (i * 10);
if(t == y) {
printf("%d\n", p.s + 1);
return;
}
if(f[t]) {
if(vis[t])
continue;
vis[t] = true;
q.push((node){t, p.s + 1});
}
}
}
}
printf("-1\n");
}
int main() {
INIT();
int n;
scanf("%d", &n);
while(n--) {
scanf("%d%d", &x, &y);
BFS();
}
return 0;
}