http://poj.org/problem?id=3126
大意:从一个素数到另一个素数,每次只能改变一个数,要求每次改变后的数都是素数,要求算出转换的最小次数,简单BFS,不过注意d要还原
/************************************************ * Author :Powatr * Created Time :2015-8-9 16:09:31 * File Name :F.cpp ************************************************/ #include <cstdio> #include <algorithm> #include <iostream> #include <sstream> #include <cstring> #include <cmath> #include <string> #include <vector> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <set> #include <bitset> #include <cstdlib> #include <ctime> using namespace std; #define lson l, mid, rt << 1 #define rson mid + 1, r, rt << 1 | 1 typedef long long ll; const int MAXN = 1e5 + 10; const int INF = 0x3f3f3f3f; const int MOD = 1e9 + 7; int a[5], b[5]; int vis[110150]; queue<pair<int, int> > q; int prim[21015]; void inti() { for(int i = 1000; i < 10000; i++){ for(int j = 2; j <i/2; j++){ if(i%j == 0) {prim[i] = 1;break;} } } } int main(){ int T; int n, m; memset(prim, 0, sizeof(prim)); scanf("%d", &T); inti(); while(T--){ memset(vis, 0, sizeof(vis)); scanf("%d%d", &n, &m); a[1] = n/1000, a[2] = n%1000/100, a[3] = n%100/10, a[4] = n%10; while(!q.empty()) q.pop(); q.push(make_pair(n, 0)); while(!q.empty()){ int x = q.front().first, y = q.front().second; q.pop(); if(vis[x]) continue; vis[x] = 1; // printf("%d ", x); a[1] = x/1000, a[2] = x%1000/100, a[3] = x%100/10, a[4] = x%10; if(x == m){ printf("%d ", y); break; } for(int i = 1; i <= 9; i++){ int k = i*1000 + a[2]*100 + a[3]*10 + a[4]; if(!prim[k]) q.push(make_pair(k,y+1)); } for(int i = 0; i <= 9; i++){ int k = a[1]*1000 + i*100 + a[3]*10 + a[4]; if(!prim[k]) q.push(make_pair(k, y+1)); } for(int i = 0 ; i <= 9; i++){ int k = a[1]*1000 + a[2]*100 + i*10 + a[4]; if(!prim[k]) q.push(make_pair(k,y+1)); } for(int i = 0; i <= 9; i++){ int k = a[1]*1000 + a[2]*100 + a[3]*10 + i; if(!prim[k]) q.push(make_pair(k,y+1)); } } } return 0; }