POJ 3126 Prime Path 素数筛+bfs

题目链接:http://poj.org/problem?id=3126

#include <iostream>
#include <time.h>
#include<stdlib.h>
#include<math.h>
#include<cstdio>
#include<queue>
using namespace std;
const int maxn=10010;
bool vis[maxn];
int prime[maxn/3];
void prime_o(int n)
{
    int x=0;
    for(int i=2;i<=n;i++)
    {
        if(vis[i]==0)prime[x++]=i;
        for(int j=0;j<x;j++)
        {
            if(i*prime[j]>n)break;
            vis[i*prime[j]]=1;
            if(i%prime[j]==0)break;
        }
    }
}
struct node 
{
    int x;
    int step;
};
int changone(int v,int wei,int num)
{
    if(wei==1)
    {
        return v/10*10+num;
    }
    if(wei==2)
    {
        return v/100*100+num*10+v%10;
    }
    if(wei==3)
    {
        return v/1000*1000+num*100+v%100;
    }
    if(wei==4)
    {
        return num*1000+v%1000;
    }
}
int bfs(int s,int e)
{
    node a;
    bool vis2[maxn]={0};
    a.x=s;
    a.step=0;
    queue<node> q;
    vis2[a.x]=1;
    q.push(a);
    while(!q.empty())
    {
        a=q.front();
        q.pop();
        if(a.x==e)return a.step;
        for(int i=1;i<=4;++i)
        {
            int t=a.x;
            int st=a.step;
            for(int j=0;j<=9;++j)
            {
                a.x=changone(a.x,i,j);
                a.step=st+1;
                if(vis2[a.x]==0&&vis[a.x]==0&&a.x>=1000&&a.x<=9999)
                {
                    vis2[a.x]=1;
                    q.push(a);
                }
                
            }
            a.x=t;
            a.step=st;
        }
    }
    return -1;
}
int main()
{
    prime_o(10000);
    int n,a,b;
    cin>>n;
    while(n--)
    {
        cin>>a>>b;
        int ans=bfs(a,b);
        if(ans>=0)
        {
            cout<<ans<<endl;
        }
        else
        {
            cout<<"Impossible"<<endl;
        }
    }
      return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wow_awsl_qwq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值