poj 3126 Prime Path

题目大意:从一个素数变换到另一个素数最小需要多少步。

思路:将所有1000~10000的素数通过打表表示出来,然后依次枚举与s相差一位的数并标记,通过BFS找寻最小步数。

 

CODE:

 

 

#include <stdio.h>
#include <stdlib.h>
#include < string.h>
#include <math.h>
#include <queue>
using  namespace std;

int prime[ 10001];
int vis[ 10001];
int flag[ 10001];
int tot;
int s, e;

struct node
{
     int x, step;
};


void init()
{
    tot =  0;
     for( int i =  2; i <=  10000; i++)  if(!vis[i])
    {
         for( int j = i*i; j <=  10000; j += i)
            vis[j] =  1;
    }
     for( int i =  1000; i <=  10000; i++)  if(!vis[i])
        prime[tot++] = i;
}


int check( int x,  int y)
{
     int cnt =  0;
     while(x)
    {
         int xx = x% 10;
         int yy = y% 10;
         if(xx != yy) cnt++;
        x /=  10;
        y /=  10;
    }
     if(cnt ==  1return  1;
         return  0;
}


int bfs()
{
    queue<node> Q;
    node p, q;
    p.x = s;
    flag[s] =  1;
    p.step =  0;
    Q.push(p);
     while(!Q.empty())
    {
        p = Q.front();
        Q.pop();
         if(p.x == e)
        {
            printf( " %d\n ", p.step);
             return  1;
        }
         for( int i =  0; i < tot; i++)
        {
            q = p;
            q.x = prime[i];
             if(check(p.x, q.x) && !flag[q.x])
            {
                q.step++;
                flag[q.x] =  1;
                Q.push(q);
            }
        }
    }
     return  0;
}


int main()
{
    init();
     int T;
    scanf( " %d ", &T);
     while(T--)
    {
        memset(flag,  0sizeof(flag));
        scanf( " %d%d ", &s, &e);
         if(s == e)
        {
            printf( " 0\n ");
             continue;
        }
         int t = bfs();
         if(!t) printf( " impossible\n ");
    }
}

 

你可能感兴趣的:(Path)