Number Transformation (bfs) (素数筛选)



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!

这道题先得到1000以内的素数,然后bfs,通过这道题,才开始理解bfs的用法,唉,路还很远啊

#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
#define N 1001
int prime[N],cnt;
int step[N];
bool b[N];
int s,t;
void filter()
{
    int i,j;
    for(i=2;i<N;i++)
    {
        if(b[i])
        {
            prime[cnt++]=i;
            for(j=i<<1;j<N;j+=i)    b[j]=false;
        }
    }
}
void init()
{
    memset(b,true,sizeof(b));
    cnt=0;
}
void bfs()
{
    queue<int> q;
    bool success=false;
    int ans,cur,next;
    memset(step,-1,sizeof(step));
    q.push(s);
    step[s]=0;
    while(!q.empty() && !success)
    {
        cur=q.front();
        q.pop();
        if(cur==t)
        {
            success=true;
            ans=step[cur];
        }
        for(int i=0;prime[i]<cur && !success;i++)
        {
            next=cur+prime[i];
            if(next>t)  continue;
            if(step[next]==-1)
            {
                step[next]=step[cur]+1;
                if(next==t)
                {
                    success=true;
                    ans=step[next];
                }
                else    q.push(next);
            }
        }
    }
    if(success) printf("Need %d step(s)\n",ans);
    else    puts("No path!");
}
int main()
{
    init();
    filter();
    while(~scanf("%d%d",&s,&t)) bfs();
    return 0;
}

这是高手的代码,细细品味后,果然博大精深,值得好好研究。。。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值