POJ3126 (BFS)

题意:从一个素数变到另一个素数,中途只能改变一个位上的数而且改变后还是素数。

方法:先打素数表,再BFS

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
const int maxn=10005;
const double eps=1e-8;
const double PI = acos(-1.0);
struct node
{
    int x,step;
};
node s,e;
bool vis[maxn],prime[maxn];
void make()
{
    memset(prime,1,sizeof(prime));
    prime[1]=0;
    for(int i=2;i<maxn;i++)
    {
        if(prime[i])
        for(int j=i*i;j<maxn;j+=i)
        {
            prime[j]=0;
        }
    }
}
int change(int x,int i,int j)
{
    if(i==1)
    {
        x = x/10*10+j;
    }
    if(i==2)
    {
        x=x/100*100+j*10+x%10;
    }
    if(i==3)
    {
        x=x/1000*1000+j*100+x%100;
    }
    if(i==4)
    {
        x=j*1000+x%1000;
    }
    return x;
}
void bfs()
{
    memset(vis,0,sizeof(vis));
    queue<node> q;
    q.push(s);
    while(!q.empty())
    {
        node t=q.front();
        if(t.x==e.x)
        {
            cout<<t.step<<endl;
            break;
        }
        q.pop();
        for(int i=1; i<=4; i++)
        {
            for(int j=0; j<=9; j++)
            {
                if(i==4&&j==0)
                {
                    continue;
                }
                int te=change(t.x,i,j);
                if(!vis[te]&&prime[te])
                {
                    node n;
                    n.step=t.step+1;
                    n.x=te;
                    q.push(n);
                    vis[te]=1;
                }
            }
        }
    }
    if(q.empty())
    {
        cout<<"Impossible"<<endl;
    }
}
int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    std::cout.tie(0);
    int t;
    cin>>t;
    make();
    while(t--)
    {
        cin>>s.x>>e.x;
        s.step=0,e.step=0;
        bfs();
    }
    return 0;
}

 

posted @ 2018-08-06 14:32  MCQ  阅读(96)  评论(0编辑  收藏  举报