POJ3126Prime Path(BFS)

来源:互联网 发布:软件项目风险控制措施 编辑:程序博客网 时间:2024/06/07 23:03
#include<iostream>#include<cstdio>#include<set>#include<string>#include<string.h>#include<cstring>#include<vector>#include<map>#include<queue>#include<stack>#include<cctype>#include<algorithm>#include<sstream>#include<utility>#include<cmath>#include<functional>#define mt(a) memset(a,0,sizeof (a))#define fl(a,b,c) fill(a,b,c)#define SWAP(a,b,t) (t=a,a=b,b=t)#define inf 1000000000+7using namespace std;typedef long long ll;#define sp system("pause")int vis[10000 + 20];bool isPrime(int x){for (int i = 2; i*i <= x; i++)if (x%i == 0)return false;return true;}class node {public:int temp, cot;};int main(){int T;cin >> T;while (T--){int a, b;cin >> a >> b;node start;memset(vis, 0, sizeof vis);start.cot = 0;start.temp = a;queue<node>q;q.push(start);vis[a] = 1;int ans = -1;while (!q.empty()){node c = q.front();q.pop();if (c.temp == b){ans = c.cot;}c.cot++;for (int i = 1; i < 10; i++){node  t = c;t.temp -= (t.temp / 1000) * 1000 - i * 1000;if (isPrime(t.temp) && !vis[t.temp])vis[t.temp] = 1, q.push(t);}for (int i = 0; i < 10; i++){node t = c;t.temp -= (t.temp%1000 / 100) * 100 - i * 100;if (isPrime(t.temp) && !vis[t.temp])vis[t.temp] = 1, q.push(t);t = c;t.temp -= (t.temp%1000%100 / 10) * 10 - i * 10;if (isPrime(t.temp) && !vis[t.temp])vis[t.temp] = 1, q.push(t);t = c;t.temp -= (t.temp%1000%100%10 )  - i ;if (isPrime(t.temp) && !vis[t.temp])vis[t.temp] = 1, q.push(t);}}if (ans != -1)cout << ans << "\n";else cout << "Impossible\n";}return 0;}

0 0