POJ 3126

思路:BFS,最先找到的必定是最小解。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<cmath>
#define MAX 11111
using namespace std;
int isprime[MAX], pre[MAX];
queue<int>q;
void Chose_Prime(){
    isprime[0] = isprime[1] = 0;
    for(int i = 2;i < MAX;i ++){
        if(!isprime[i]){
            for(int j = i + i;j < MAX;j += i)
                isprime[j] = 1;
        }
    }
}
int Switch(int num, int i, int j){
    int target = num/(int)pow(10., 3-i);
    int temp = target%10;
    return num += (j - temp)*(int)pow(10., 3-i);
}
int bfs(int st, int end){
    int rr;
    while(!q.empty()) q.pop();
    q.push(st);
    pre[st] = 0;
    while(!q.empty()){
        int p = q.front();
        q.pop();
        for(int i = 0;i < 4;i ++){
            for(int j = 0;j <= 9;j ++){
                if(i + j){
                    rr = Switch(p, i, j);
                    if(!isprime[rr] && pre[rr] == -1){
                        pre[rr] = p;
                        q.push(rr);
                        if(rr == end) return true;
                    }
                }
            }
        }
    }
    return false;
}
int main(){
    int T, a, b, ans;
    Chose_Prime();
    //freopen("in.c", "r", stdin);
    cin >> T;
    while(T--){
        memset(pre, -1, sizeof(pre));
        ans = 0;
        cin >> a >> b;
        if(a == b){
            cout << 0 << endl;
            continue;
        }
        if(bfs(a, b)){
            while(pre[b] != 0){
                ans ++;
                b = pre[b];
            }
            cout << ans << endl;
        }else{
            cout << "impossible" << endl;
        }
    }
    return 0;
}


原文地址:https://www.cnblogs.com/anhuizhiye/p/3933218.html