F - Prime Path POJ - ( Prime +BFS)

注意判断前导0

注意改变temp1的多次使用的值时

要先暂时存储一下然后使用完之后恢复

#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
#define maxn 10000
bool isprime[maxn]= {0};
void prime()
{
    isprime[0]=isprime[1]=1;
    for(int i=2; i<maxn; i++)
        for(int j=i*i; j<maxn; j+=i)
            isprime[j]=1;
}
struct node
{
    int x,step;
} temp1,temp2;
int n,m,t[5],ans,cnt,temp;
void bfs()
{
    bool vis[maxn]= {0};
    queue<node>q;
    temp1.x=n;
    temp1.step=0;
    q.push(temp1);
    vis[temp1.x]=1;
    while(!q.empty())
    {
        temp1.x=q.front().x;
        temp1.step=q.front().step;
        if(temp1.x==m)
        {
            ans=temp1.step;
            return ;
        }
        t[0]=temp1.x/1000;
        t[1]=temp1.x%1000/100;
        t[2]=temp1.x%100/10;
        t[3]=temp1.x%10;
        q.pop();
        for(int i=0; i<4; i++)
        {
            temp=t[i];
            for(int j=0; j<10; j++)
            {
                if((i==0||i==3)&&j==0)
                    continue;
                if(j!=temp)
                {
                    t[i]=j;
                    temp2.x=t[0]*1000+t[1]*100+t[2]*10+t[3];
                    temp2.step=temp1.step+1;
                    if(!vis[temp2.x]&&!isprime[temp2.x])
                    {
                        q.push(temp2);
                        vis[temp2.x]=1;
                    }
                }
            }
            t[i]=temp;
        }
    }
}
int main()
{
    prime();
    int t;
    cin>>t;
    while(t--)
    {
        cin>>n>>m;
        bfs();
        cout<<ans<<endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值