Number Transformation (bfs+素因子)

    1141 - Number Transformation
Time Limit: 2 second(s)Memory Limit: 32 MB

In this problem, you are given an integer number s.You can transform any integer number A to another integer number Bby adding x to A. This x is an integer number which is aprime factor of A (please note that 1 and Aare not beingconsidered as a factor of A). Now, your task is to find the minimumnumber of transformations required to transform s to another integernumber t.

Input

Input starts with an integer T (≤ 500),denoting the number of test cases.

Each case contains two integers: s (1 ≤ s ≤100) and t (1 ≤ t ≤ 1000).

Output

For each case, print the case number and the minimum numberof transformations needed. If it's impossible, then print -1.

Sample Input

Output for Sample Input

2

6 12

6 13

Case 1: 2

Case 2: -1

题目大意:给你两个数s和t,s加上s的一个素因子得到新的s,问至少这样几步可以使得s变成t。
代码:

#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int c[1100][6]= {0},lu[1010],a,b;

struct yun
{
    int x,s;
};

int bfs(int x)
{
    yun st,en;
    queue<yun>Q;
    st.x=x;
    st.s=0;
    Q.push(st);
    while(Q.size())
    {
        st=Q.front();
        Q.pop();
        for(int i=1; i<=5; i++)//1000以内的数的素因子最多不超多5个;
        {
            int dx=st.x+c[st.x][i];
            if(lu[dx]||dx>b)continue;//判重,是否越界;
            lu[dx]=1;//标记;
            en.x=dx;
            en.s=st.s+1;
            if(en.x==b)
                return en.s;
            Q.push(en);
        }
    }
    return -1;
}

int prime(int q)//
{
    for(int i=2; i<q; i++)
        if(q%i==0)return 0;
    return 1;
}

int main()
{
    int m,i,j,t,f=1;
    c[1][1]=0;
    c[2][1]=0;
    for(i=3; i<=1000; i++)//从1到1000的数的素因子打表;
    {
        for(j=2,t=0; j<i; j++)
        {
            if(i%j==0&&prime(j))
            {
                c[i][++t]=j;
            }
        }
    }
    scanf("%d",&m);
    while(m--)
    {
        scanf("%d%d",&a,&b);
        memset(lu,0,sizeof(lu));
        lu[a]=1;
        if(a==b)printf("Case %d: 0\n",f++);
        else
            printf("Case %d: %d\n",f++,bfs(a));
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值