POJ 3126
#include<iostream> #include<queue> #include<string> using namespace std; const int M = 10000; int prime[M],pn; bool notprime[M]; void init() { pn = 0; notprime[1] = 1; for(int i = 2; i < M; i++) { if(notprime[i] == 0) prime[pn++] = i; for(int j = 0; j < pn && prime[j]*i < M; j++) { notprime[prime[j]*i] = 1; if(i%prime[j] == 0) break; } } } int vis[M]; struct node{ int x,step; }; queue<node>q; int bfs(int n, int m) { node first_node; first_node.step = 0; first_node.x = n; q.push(first_node); vis[n] = 1; //标记n走过 node next; while(!q.empty()) { node tmp = q.front(); int x = tmp.x; q.pop(); if(x == m) return tmp.step; //如果到了终点 int num_1 = x/1000, num_2 = (x%1000)/100, num_3 = (x-num_1*1000-num_2*100)/10, num_4 = x%10; //千位 for(int i = 1; i < 10; i++) { int num = i*1000 + num_2*100 + num_3*10 + num_4; if(!vis[num] && !notprime[num]) { next.x = num; next.step = tmp.step + 1; q.push(next); vis[num] = 1; } } //百位和十位 for(int i = 0; i < 10; i++) { int num = num_1*1000 + i*100 + num_3*10 + num_4; if(!vis[num] && !notprime[num]) { next.x = num; next.step = tmp.step + 1; q.push(next); vis[num] = 1; } num = num_1*1000 + num_2*100 + i*10 + num_4; if(!vis[num] && !notprime[num]) { next.x = num; next.step = tmp.step + 1; q.push(next); vis[num] = 1; } } //个位 for(int i = 1; i < 10; i = i+2) { int num = num_1*1000 + num_2*100 + num_3*10 + i; if(!vis[num] && !notprime[num]) { next.x = num; next.step = tmp.step + 1; q.push(next); vis[num] = 1; } } } return -1; } int main() { init(); int t; cin>>t; while(t--){ while(!q.empty()) q.pop(); for(int i = 0; i < M; i++) vis[i] = 0; int n,m; cin>>n>>m; int ans = bfs(n,m); if(ans == -1) cout<<"Impossible"<<endl; else cout<<ans<<endl; } return 0; }
代码很长,思路不难。把四位数拿出来,循环看是不是素数。加上bfs就ok了。