POJ 3126 Prime Path BFS搜索

题意:就是找最短的四位数素数路径

分析:然后BFS随便搜一下,复杂度最多是所有的四位素数的个数

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cmath>
#include<map>
#include<queue>
#include<stdlib.h>
#include<string>
using namespace std;
typedef long long LL;
const int maxn=10005;
const int INF=0x3f3f3f3f;
int t,s;
int a[maxn];
bool vis[maxn];
bool fun(int x)
{
    for(int i=2; i*i<=x; ++i)
        if(x%i==0)return 0;
    return 1;
}
struct Data
{
    int b[4];
} d,e;
queue<Data>q;
int get(Data x)
{
    int ans=0;
    for(int i=3; i>=0; --i)
        ans=ans*10+x.b[i];
    return ans;
}
int main()
{
    int T;
    for(int i=1001; i<10000; ++i)
        if(fun(i))vis[i]=1;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&s,&t);
        memset(a,-1,sizeof(a));
        while(!q.empty())q.pop();
        if(!vis[s]||!vis[t])
        {
            printf("Impossible\n");
            continue;
        }
        a[s]=0;
        for(int i=0; i<4; ++i)
        {
            d.b[i]=s%10;
            s/=10;
        }
        q.push(d);
        while(!q.empty())
        {

            e=d=q.front();
            q.pop();
            int k=get(d);
            if(k==t)break;
            for(int i=0; i<4; ++i)
            {
                for(int j=0; j<10; ++j)
                {
                    if(j==d.b[i])continue;
                    e.b[i]=j;
                    int x=get(e);
                    if(!vis[x]||a[x]>=0)continue;
                    a[x]=a[k]+1;
                    q.push(e);
                }
                e.b[i]=d.b[i];
            }
        }
        if(a[t]==-1)
        {
              printf("Impossible\n");
              continue;
        }
        printf("%d\n",a[t]);
    }
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/shuguangzw/p/5162859.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值