分析
- 先预处理出10000以内的素数
- BFS搜索
注意
- POJ的编译器比较老,C++11的语法会编译不通过。
代码
#include <iostream>
#include <string>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <utility>
#include <queue>
using namespace std;
/*
* 1. 先用素数筛出10000下的素数
* 2. 再BFS搜
*
*/
int k;
struct Node{
string v;
int d;
Node(string v_, int d_){
v = v_;
d = d_;
}
};
const int N = 10010;
typedef long long LL;
int pm[N];
bool st[N];
bool vis[N];
void getPrimes() {
for(int i = 2; i < N; i++) {
if(!st[i]) pm[k++] = i;
for(int j = 0; pm[j] * (LL)i < N; j++) {
st[pm[j]*i] = true;
if(i % pm[j] == 0) break;
}
}
}
typedef pair<string, int> PII;
int STI(string n){
return (n[0]-'0')*1000+(n[1]-'0')*100+(n[2]-'0')*10+(n[3]-'0');
}
int main() {
memset(pm, 0, sizeof pm);
memset(st, 0, sizeof st);
getPrimes();
int n;
cin >> n;
while(n--) {
string start, end;
cin >> start >>end;
if(st[STI(end)]) puts("Impossible");
else{
//bfs
queue<Node> q;
memset(vis, 0, sizeof vis);
Node node(start, 0);
q.push(node);
vis[STI(start)] = true;
int ans = -1;
while(q.size()) {
Node t = q.front();
string v = t.v;
int d = t.d;
if(v == end) {
ans = d;
break;
}
q.pop();
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 10; j++) {
if(i == 0 && j == 0) continue;
string temp = v;
if(temp[i] == j + '0') continue;
temp[i] = j + '0';
if(vis[STI(temp)]) continue;
Node node(temp, d+1);
if(!st[STI(temp)]) q.push(node);
vis[STI(temp)] = true;
}
}
}
if(ans == -1) puts("Impossible");
else cout<<ans<<endl;
}
}
return 0;
}