题目传送:Prime Path
思路:上次选拔赛的题,简单BFS,当时没有做出来,突然发现自己当时是多么的弱。。一个简单搜索都不会。。这里只要先筛出1000到10000的素数,然后再用队列模拟一下其过程即可,用结构体存下当前素数以及当前所在的层次,即本题所求的最小步数,当时好像就是这里没想通怎么实现最小步数跪的
AC代码:
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <deque>
#include <cctype>
#define LL long long
#define INF 0x7fffffff
using namespace std;
int T;
int sum;
int prime[10005];
int vis[10005];
int judge(int x) {
int m = sqrt(x);
for(int i = 2; i <= m; i ++) {
if(x % i == 0) return 0;
}
return 1;
}
int fun(int a, int b) {//判断两素数是否只有一个数字不同
int ret = 0;
while(a) {
if(a % 10 == b % 10) ret ++;
a /= 10;
b /= 10;
}
if(ret == 3) return 1;
else return 0;
}
void init() {//筛出素数
sum = 0;
for(int i = 1000; i < 10000; i ++) {
if(judge(i)) prime[sum ++] = i;
}
}
struct node {
int num;
int cnt;
node(int n, int c) : num(n), cnt(c) {};
};
int bfs(int a, int b) {//bfs找最小步数
if(a == b) return 0;
memset(vis, 0, sizeof(vis));
queue<node> que;
que.push(node(a, 0));
vis[a] = 1;
while(!que.empty()) {
node t = que.front();
que.pop();
for(int i = 0; i < sum; i ++) {
if(!vis[prime[i]] && fun(prime[i], t.num)) {
node n0 = node(prime[i], t.cnt + 1);
if(n0.num == b) return n0.cnt;
que.push(n0);
vis[prime[i]] = 1;
}
}
}
}
int main() {
init();
scanf("%d", &T);
while(T --) {
int a, b;
scanf("%d %d", &a, &b);
printf("%d\n", bfs(a, b));
}
return 0;
}