Number Transformation

Description

 In this problem, you are given a pair of integers A and B. You can transform any integer number A to B by adding x to A.This x is an integer number which is a prime below A.Now,your task is to find the minimum number of transformation required to transform S to another integer number T.

Input

 Input contains multiple test cases.Each test case contains a pair of integers S and T(0< S < T <= 1000) , one pair of integers per line. 

Output

 For each pair of input integers S and T you should output the minimum number of transformation needed as Sample output in one line. If it's impossible ,then print 'No path!' without the quotes.

Sample Input

5
7
3
4

Sample Output

Need 1 step(s)
No path!
//从A->B能转化的要求是存在一个质数x,使得x<A ,而且A+x == B 。
//首先我们可以用线性筛素法筛出所有的素数,然后就是bfs搜索就可以了。

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
const int MAXN = 1050 ;

struct Node
{
    int num ,d ;
    Node() {};
    Node(int a, int b):num(a),d(b) {}
};
bool prim[MAXN] ;
bool mark[MAXN] ;
int C , S ,T ;

void isprim()
{
    for(int i = 2 ; i < MAXN ; i ++)
        prim[i] = 1 ;
    for(int i = 2 ; i < MAXN ; i ++)
        if(prim[i])
            for(int j = 2 ; i * j < MAXN ; j ++)
                prim[i * j] = 0 ;
}

int bfs(int source , int destation)
{
    queue<Node> Q ;
    memset(mark , 0 , sizeof(mark)) ;
    Node a ;
    Q.push( Node(source , 0) )  ;
    mark[source] = 1 ;
    while( !Q.empty() )
    {
        a = Q.front() ;
        Q.pop() ;
        //搜索比它小的素数
        for(int i = 2 ; i < a.num ; i ++)
        {
            //判断要加的数是不是素数
            if(!prim[i] )continue ;

            int number = a.num + i ;
            //大于所要求的目标数,直接退出
            if(number > destation) break ;
            if(mark[number]) continue ;

            mark[number] = 1 ;
            if(number == destation)
                return a.d + 1;
            Q.push( Node(number , a.d+1) ) ;
        }
    }
    return -1 ;
}

int main()
{
    isprim() ;
    while( scanf("%d%d" , &S , &T) == 2 )
    {
        int d = bfs(S , T) ;
        if(d==-1) printf("No path!\n") ;
        else      printf("Need %d step(s)\n" , d) ;
    }
    return 0 ;
}
BFS

 

posted @ 2013-09-06 20:41  1002liu  阅读(235)  评论(0编辑  收藏  举报