ac代码:
#include <iostream> #include <time.h> #include<stdlib.h> #include<math.h> #include<cstdio> #include<queue> using namespace std; const int maxn=10010; bool vis[maxn]; int prime[maxn/3]; void prime_o(int n) { int x=0; for(int i=2;i<=n;i++) { if(vis[i]==0)prime[x++]=i; for(int j=0;j<x;j++) { if(i*prime[j]>n)break; vis[i*prime[j]]=1; if(i%prime[j]==0)break; } } } struct node { int x; int step; }; int changone(int v,int wei,int num) { if(wei==1) { return v/10*10+num; } if(wei==2) { return v/100*100+num*10+v%10; } if(wei==3) { return v/1000*1000+num*100+v%100; } if(wei==4) { return num*1000+v%1000; } } int bfs(int s,int e) { node a; bool vis2[maxn]={0}; a.x=s; a.step=0; queue<node> q; vis2[a.x]=1; q.push(a); while(!q.empty()) { a=q.front(); q.pop(); if(a.x==e)return a.step; for(int i=1;i<=4;++i) { int t=a.x; int st=a.step; for(int j=0;j<=9;++j) { a.x=changone(a.x,i,j); a.step=st+1; if(vis2[a.x]==0&&vis[a.x]==0&&a.x>=1000&&a.x<=9999) { vis2[a.x]=1; q.push(a); } } a.x=t; a.step=st; } } return -1; } int main() { prime_o(10000); int n,a,b; cin>>n; while(n--) { cin>>a>>b; int ans=bfs(a,b); if(ans>=0) { cout<<ans<<endl; } else { cout<<"Impossible"<<endl; } } return 0; }