Prime Path

来源:互联网 发布:linux 内核经典代码 编辑:程序博客网 时间:2024/06/12 23:44

题意:给两个数st、ed,每次st可以任意改变一位数字,要求只能走素数,求从st到ed的最小步数

解题思路:专题——简单搜索.bfs求最短路,求出每一位然后枚举改变每一位的情况,如果是素数就加入队列

代码:

#include <iostream>#include <algorithm>#include <cstring>#include <string>#include <cstdio>#include <cmath>#include <vector>#include <queue>using namespace std;#define INF 0x3f3f3f3fint st,ed;int dist[10005];int gw0,sw0,bw0,qw0;void init(int p){    int tt=p;    gw0=tt%10;    tt/=10;    sw0=tt%10;    tt/=10;    bw0=tt%10;    tt/=10;    qw0=tt%10;}bool is_prime(int x){    for(int i=2; i*i<=x; i++)    {        if(x%i==0)return false;    }    return true;}int bfs(int x){    for(int i=1000; i<=9999; i++)    {        dist[i]=INF;    }    queue<int> que;    que.push(x);    dist[x]=0;    while(!que.empty())    {        int p=que.front();que.pop();        if(p==ed)break;        init(p);        for(int i=1; i<=9; i++)        {            int temp=i*1000+bw0*100+sw0*10+gw0;            if(is_prime(temp)&&dist[temp]==INF)            {                dist[temp]=dist[p]+1;                que.push(temp);            }        }        for(int i=0; i<=9; i++)        {            int temp=qw0*1000+i*100+sw0*10+gw0;            if(is_prime(temp)&&dist[temp]==INF)            {                dist[temp]=dist[p]+1;                que.push(temp);            }        }        for(int i=0; i<=9; i++)        {            int temp=qw0*1000+bw0*100+i*10+gw0;            if(is_prime(temp)&&dist[temp]==INF)            {                dist[temp]=dist[p]+1;                que.push(temp);            }        }        for(int i=0; i<=9; i++)        {            int temp=qw0*1000+bw0*100+sw0*10+i;            if(is_prime(temp)&&dist[temp]==INF)            {                dist[temp]=dist[p]+1;                que.push(temp);            }        }    }    return dist[ed];}int main(){    int T;    cin>>T;    while(T--)    {        cin>>st>>ed;        int ans=bfs(st);        cout<<ans<<endl;    }    return 0;}/*31033 81791373 80171033 1033*/