Number Transformation 【LightOJ - 1141】

In this problem, you are given an integer number s. You can transform any integer number A to another integer number B by adding x to A. This x is an integer number which is a prime factor of A (please note that 1 and A are not being considered as a factor of A). Now, your task is to find the minimum number of transformations required to transform s to another integer number 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 number of transformations needed. If it's impossible, then print -1.

Sample Input

2

6 12

6 13

Sample Output

Case 1: 2

Case 2: -1

题意:

求一个数 S 与它的质因数相加等于 T 最少需要几步。如果不可能,输出 -1.

用bfs。

代码:

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

int a,b,s[1100],book[1100],f;

void prime()
{
    memset(s,0,sizeof(s));
    for(int i = 2; i < 1010; i ++)
    {
        if(s[i] == 0)
        {
            for(int j = i*2; j <1010; j += i)
                s[j]=1;
        }
    }
}

struct node
{
    int x,y;
};

void bfs(int x)
{
    queue<node>q;
    node now,temp;
    now.x=x;
    now.y=0;
    book[x]=1;
    q.push(now);
    while(!q.empty())
    {

        temp=q.front();
        q.pop();
        for(int i = 2; i < temp.x; i ++)
        {
            if(temp.x%i == 0 &&s[i] == 0)
            {
                int c=temp.x+i;
                if(book[c] == 1||c > b)
                    continue;
                book[c]=1;
                now.x=c;
                now.y=temp.y+1;
                if(c == b)
                {
                    f=now.y;
                    return ;
                }
                q.push(now);
            }
        }
    }
    return ;
}

int main()
{
    int t,k=1;
    scanf("%d",&t);
    prime();
    while(t--)
    {
        f=0;
        memset(book,0,sizeof(book));
        scanf("%d%d",&a,&b);
        if(a == b)
            printf("Case %d: 0\n",k++);
        else
        {
            bfs(a);
            if(f)
                printf("Case %d: %d\n",k++,f);
            else
                printf("Case %d: -1\n",k++);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Meant_To_Be/article/details/81225750
今日推荐