POJ - 3126 - Prime Path 【BFS + 素数打表】

题意:给你两个四位数的素数,让你从第一个素数变成第二个,每次操作只能改动一位数字,且需要保证改动后的数字任为为素数;输出需要操作多少次; 

题解:先素数打表,BFS处理时将满足条件的数字放入队列中(未被访问过且为素数,与队列front()的元数只有一位数字不同);

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<cmath>
#define INF 0x7ffffff
using namespace std;
const int maxn = 1e4+5;
bool prime[maxn];
int T, s, e;
void is_prime()
{
    memset(prime, 1, sizeof(prime));
    int m = sqrt(maxn);
    prime[0] = prime[1] = false;
    for (int i = 2; i < m; i++)
    {
        if(prime[i])
        {
            for (int j = i * i; j < maxn; j += i)
            {
                prime[j] = false;
            }
        }
    }
}
bool Judge(int a, int b)
{
    int cnt = 0;
    if(a%10 != b%10) cnt++;
    if(a%100/10 != b%100/10) cnt++;
    if(a%1000/100 != b%1000/100) cnt++;
    if(a/1000 != b/1000) cnt++;
    if(cnt == 1) return true;
    return false;
}
int bfs()
{
    bool vis[10000];
    memset(vis, 0, sizeof(vis));
    pair<int, int> Now;
    Now.first = s, Now.second = 0;
    queue<pair<int, int> > q;
    vis[s] = true;
    q.push(Now);
    while(!q.empty())
    {
        Now = q.front();
        if(Now.first == e)
        {
            return Now.second;
        }
        q.pop();
        for (int i = 1000; i < 10000; i++)
        {
            if(prime[i] && !vis[i] && Judge(i, Now.first))
            {
                vis[i] = true;
                q.push(make_pair(i, Now.second + 1));
            }
        }
    }
    return -1;
}
int main()
{
    is_prime();
    scanf("%d", &T);
    while(T--)
    {
        scanf("%d%d", &s, &e);
        int ans = bfs();
        if(ans != -1)
            printf("%d\n",ans);
         else
            printf("Impossible\n");
    }
}

 

阅读更多

没有更多推荐了,返回首页