POJ(3126)素数+bfs


http://poj.org/problem?id=3126


#include <iostream>
#include <queue>
#include <cstring>
#include <stdio.h>
using namespace std;
#define MAXV 10000
bool prime[MAXV];
int ans[MAXV];
void init()
{
    int tot=0;
    memset(prime,0,sizeof(prime));
    for(int i=2; i<=MAXV; i++)
    {
        if(!prime[i])
            ans[++tot]=i;
        for(int j=1; j<tot&&i*ans[j]<=MAXV; j++)
        {
            prime[i*ans[j]]=1;
            if(i%ans[j]==0)
                break;
        }
    }
}
int bfs(int first,int last)
{
    bool dis[MAXV];
    queue <int>q;
    int v,i,j,temp,vtemp,count[MAXV],t[4];
    memset(dis,false,sizeof(dis));
    memset(count,0,sizeof(count));

    q.push(first);
    dis[first]=true;

    while(!q.empty())
    {
        v=q.front();
        q.pop();

        t[0]=v/1000;
        t[1]=v%1000/100;
        t[2]=v%100/10;
        t[3]=v%10;
//		printf("%d %d %d %d",t[0],t[1],t[2],t[3]);

        for(j=0; j<4; j++)
        {
            temp=t[j];
            for(i=0; i<10; i++)
                if(i!=temp)
                {
                    t[j]=i;
                    vtemp=t[0]*1000+t[1]*100+t[2]*10+t[3];
                    if(!dis[vtemp] && !prime[vtemp])
                    {
                        count[vtemp]=count[v]+1;
                        dis[vtemp]=true;
                        q.push(vtemp);
                    }
                    if(vtemp==last) return count[vtemp];
                }
            t[j]=temp;
        }
        if(v==last) return count[v];
    }
    return -1;
}

int main()
{
    int n,a,b,key;
    init();
    scanf("%d",&n);
    while(n--)
    {
        scanf("%d%d",&a,&b);
        key=bfs(a,b);
        if(key!=-1) printf("%d\n",key);
        else printf("Impossible\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/beposit/article/details/80719313