POJ3126 (BFS)

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

方法:我的bfs超时了,运行的很慢,看的标程,借助两个数组模拟du队列。

#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;

const int maxn=10000;
const double eps=1e-8;
const double PI = acos(-1.0);
int prime[10000],s[10000];
struct node
{
    int n,step;
};
void make()
{
    int i,j;
    memset(prime,1,sizeof(prime));
    prime[0]=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 a,int i,int j)
{
    if(i==1)
    {
        a=a/10*10+j;
    }
    if(i==2)
    {
        a=(a/100)*100+j*10+a%10;
    }
    if(i==3)
    {
        a=a/1000*1000+j*100+a/10%10*10+a%10;
    }
    if(i==4)
    {
        a=a%1000+j*1000;
    }
    return a ;
}
int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    int t,x,y;
    make();
    cin>>t;
    while(t--)
    {
        cin>>x>>y;
        node h[10000];
        h[1].n=x;
        h[1].step=0;
        memset(s,100,sizeof(s));
        int ans=-1,l=1,r=1;
        while(1)
        {
            if(h[l].n==y)
            {
                ans=h[l].step;
                break;
            }
            int tk,ts;
            for(int i=1; i<=4; i++)
            {
                for(int j=0; j<=9; j++)
                {
                    if(!j&&i==4)
                    {
                        continue;
                    }
                    tk=change(h[l].n,i,j);
                    if(!prime[tk])
                    continue;
                    ts=h[l].step+1;
                    if(ts>=s[tk])
                    {
                        continue;
                    }
                    if(tk==y)
                    {
                        ans=ts;
                        break;
                    }
                    s[tk]=ts;
                    r++;
                    h[r].n=tk;
                    h[r].step=ts;
                }

            }
            if(l==r||ans>=0)
                    break;
                l++;
        }
        if(ans>=0)
        {
            cout<<ans<<endl;
        }
        else
            cout<<"Impossible"<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Dilly__dally/article/details/81453799