poj 3126

本文解析了一道关于数字变换的搜索题,采用广度优先搜索算法,通过将数字转换为相邻素数来寻找最短路径。代码实现包括素数判断、广度优先搜索等关键步骤。

一道搜索的水题,其实搜索相对其他的来说好掌握一点,因为有个固定的模板可以用去套

题目大意就是数字的变化,一个数字只可以变化到它最相邻的一个素数上去,意思是只变化一位数字,求最短的变化方案

 

#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <queue>

bool mark [10001];

int s[10001],step[10001],ans;


using namespace std;

queue<int >q;

int bfs(int x)
{
    int head,c[4],y,i;
    if(x==ans)
    {
        printf("0\n");
        return 0;
    }
    while(!q.empty())
        q.pop();
    q.push(x);
    mark[x]=false;
    while(!q.empty())
    {
        head=q.front();
        q.pop();
        c[0]=head/1000;
        c[1]=(head-c[0]*1000)/100;
        c[2]=(head-c[0]*1000-c[1]*100)/10;
        c[3]=head%10;
        for(i=0;i<=9;i++)
        {
            if(i!=0)
            {
                y=1000*i+c[1]*100+c[2]*10+c[3];
                if(s[y]&&mark[y]){q.push(y);mark[y]=false;step[y]=step[head]+1;}
            }
            y=c[0]*1000+100*i+c[2]*10+c[3];
            if(s[y]&&mark[y]){q.push(y);mark[y]=false;step[y]=step[head]+1;}
            y=c[0]*1000+c[1]*100+i*10+c[3];
            if(s[y]&&mark[y]){q.push(y);mark[y]=false;step[y]=step[head]+1;}
            y=c[0]*1000+c[1]*100+c[2]*10+i;
            if(s[y]&&mark[y]){q.push(y);mark[y]=false;step[y]=step[head]+1;}
        }
        if(head==ans) printf("%d\n",step[head]);
    }
    return 0;
}
int main()
{
    int i,n,first;
    memset(s,0,sizeof(s));
    for(i=1000;i<=10000;i++)
        for(int j=2;j<=sqrt(i)+1;j++)
        {
            if(i%j==0) break;
            if(j==int(sqrt(i))) s[i]=1;
        }
    scanf("%d",&n);
    while(n)
    {
        n--;
        memset(mark,true,sizeof(mark));
        memset(step,0,sizeof(step));
        scanf("%d%d",&first,&ans);
        bfs(first);
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/Tree-dream/p/5401478.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值