poj 3126 Prime Path

简单题确实刷起来就是爽啊,原始的bfs,首先打一张素数表,然后根据表来进行素数的判断,可以省很多时间。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;
const int N = 10000;
int ans;
int pri[N];
int e1,e2,e3,e4,a,b;
bool vis[N];

typedef struct {
int cou,a1,a2,a3,a4;
}Node;

void ini()
{
    for(int i=1;i<N;++i)
     pri[i] = 1;
    for(int i=2;i<=100;++i)
    {
        if(pri[i]==1)
        {
            for(int e=2*i;e<N;e+=i)
                pri[e]=0;
        }
    }
}

void bfs()
{
    Node now,next;
    now.cou = 0; now.a1 = a/1000; now.a4 = a%10; now.a3 = (a%100)/10; now.a2 = (a/100)%10;
    queue<Node> q;
    q.push(now);
    memset(vis,true,sizeof(vis));
    while(!q.empty())
    {
        next = q.front();
        q.pop();
        if(next.a1==e1&&next.a2==e2&&next.a3==e3&&next.a4==e4)
        {
            ans = next.cou;
            return;
        }
        for(int i=1;i<10;++i)
        if(i!=next.a1)
        {
           int sum = i*1000+next.a2*100+next.a3*10+next.a4;
           if(pri[sum]&&vis[sum])
           {
               vis[sum]=false;
               now.cou = next.cou+1; now.a1 = i; now.a2 = next.a2; now.a3 = next.a3; now.a4 = next.a4;
               q.push(now);
           }
        }
        for(int i=0;i<10;++i)
        {
           int sum = next.a1*1000+i*100+next.a3*10+next.a4;
           if(pri[sum]&&vis[sum])
           {
               vis[sum]=false;
               now.cou = next.cou+1; now.a1 = next.a1; now.a2 = i; now.a3 = next.a3; now.a4 = next.a4;
               q.push(now);
           }
        }
        for(int i=0;i<10;++i)
        {
           int sum = next.a1*1000+next.a2*100+i*10+next.a4;
           if(pri[sum]&&vis[sum])
           {
               vis[sum]=false;
               now.cou = next.cou+1; now.a1 = next.a1; now.a2 = next.a2; now.a3 = i; now.a4 = next.a4;
               q.push(now);
           }
        }
        for(int i=0;i<10;++i)
        {
            int sum = next.a1*1000+next.a2*100+next.a3*10+i;
            if(pri[sum]&&vis[sum])
           {
               vis[sum]=false;
               now.cou = next.cou+1; now.a1 = next.a1; now.a2 = next.a2; now.a3 = next.a3; now.a4 = i;
               q.push(now);
           }
        }
    }
}

int main(void)
{
    ini();
    int ncase;
    cin>>ncase;
    while(ncase--)
    {
      scanf("%d %d",&a,&b);
      ans = -1;
      e1 = b/1000; e4 = b%10; e3 = (b%100)/10; e2 = (b/100)%10;
      bfs();
      if(ans == -1)
        printf("Impossible\n");
      else
        cout<<ans<<endl;
    }
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值