您的位置:首页 > 其它

BFS POJ 3126 Prime Path

2015-08-02 19:56 323 查看
题目传送门

 /*
题意:从一个数到另外一个数,每次改变一个数字,且每次是素数
BFS:先预处理1000到9999的素数,简单BFS一下。我没输出Impossible都AC,数据有点弱
*/
/************************************************
Author        :Running_Time
Created Time  :2015-8-2 15:46:57
File Name     :POJ_3126.cpp
*************************************************/

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <cstdlib>
#include <ctime>
using namespace std;

#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
typedef long long ll;
const int MAXN = 1e4 + 10;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
bool is_prime[MAXN];
bool vis[MAXN];
int x, y, res;
struct Digit    {
int d[5];
int step;
};

void solve(void)    {
memset (is_prime, true, sizeof (is_prime));
for (int i=1000; i<=9999; ++i)  {
for (int j=2; j<i; ++j)  {
if (i % j == 0) {
is_prime[i] = false;    break;
}
}
}
}

int get_num(int *a) {
int ret = 0;
for (int i=1; i<=4; ++i)    {
ret = ret * 10 + a[i];
}
return ret;
}

void BFS(int u, int v)   {
Digit tmp;
for (int i=4; i>=1; --i)    {
tmp.d[i] = u % 10;  u /= 10;
}
tmp.step = 0;
queue<Digit> Q; Q.push (tmp);   vis[u] = true;
int ans = -1;
while (!Q.empty ()) {
Digit x = Q.front ();   Q.pop ();
int m = get_num (x.d);
if (m == v) {
ans = x.step;   break;
}
for (int i=1; i<=4; ++i)    {
for (int j=0; j<=9; ++j)    {
if (i == 1 && j == 0)   continue;
if (x.d[i] != j)    {
Digit y = x;
y.d[i] = j; m = get_num (y.d);
if (is_prime[m] && !vis[m])    {
vis[m] = true;  y.step++;   Q.push (y);
}
}
}
}
}
if (ans == -1)  puts ("Impossible");
else    printf ("%d\n", ans);
}

int main(void)    {       //POJ 3126 Prime Path
solve ();
int T;  scanf ("%d", &T);
while (T--) {
scanf ("%d%d", &x, &y);
memset (vis, false, sizeof (vis));
BFS (x, y);
}

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