您的位置:首页 > 其它

POJ 3126 Prime Path(BFS)

2016-03-22 18:28 344 查看
#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+7

using 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: