G - Number Transformation BFS

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

扫描二维码关注公众号,回复: 6850739 查看本文章

Case 1: 2

Case 2: -1

思路:一开始理解错了,  这个题目的就是给你个整数s, 加他的素质数,以最小的次数转换到t,能转换为t输出叠加次数,否则输出-1;注意:这里的是素质数会随着s的而改变,即素质数的数组是变化的。

这个题目可以理解为  一个x数轴从S点,每次加上他的素质数,是否能得到t点;

AC代码

#include<iostream>
#include<queue>
#include<vector>
#include<cstring>
using namespace std;
const int N=1010;
vector<int >arr;

struct stu{
    int a;
    int s;
}e1,e2,e3;

int pri[N]={1,1,0};
int n,m;
int mark[N]={0};

int prime(){//将1010以内的素数打个表 
    for(int i=2;i*i<=N;i++){
        if(!pri[i])
        for(int j=i+i;j<=N;j+=i){
            pri[j]=1;
        }        
    }
}

void f(int x){//寻找素质数
    for(int i=2;i<x;i++){
        if(x%i==0&&pri[i]==0){
            arr.push_back(i);
        }
    }
}


int  bfs(int n,int m){//    起点与终点 
    memset(mark,0,sizeof(mark));
    queue<stu>que;
    e1.a=n;
    e1.s=0;
    que.push(e1);
    mark[n]=1;
    while(que.size()){
        e2=que.front();
        que.pop();
        arr.clear();
        f(e2.a);//更新素质数的数组
        if(arr.size()==0)
            continue ;
        for(int i=0;i<arr.size();i++){
            e3.a=e2.a+arr[i];
            if(mark[e3.a]!=1&&e3.a>=0&&e3.a<=m){
                mark[e3.a]=1;
                if(e3.a==m) return e2.s+1;
                else {
                    e3.s=e2.s+1;
                    que.push(e3);
                }
            }
        }
    }
    return -1;
}

int main()
{
    prime();
    int t;
    cin>>t;
    for(int i=1;i<=t;i++){
        cin>>n>>m;
        if(m-n==0)
        {
            int a=0;
            printf("Case %d: %d\n",i,a);
            continue ;
        }
        else if(n>m||m-n==1)//n若比M小或者相差为1  直接 -1;
        {
            int a=-1;
            printf("Case %d: %d\n",i,a);
            continue ;
            
        }
        int x=bfs(n,m);
        if(x==-1)
        {
            printf("Case %d: %d\n",i,x);
        }
        else {
            printf("Case %d: %d\n",i,x);
        }
    }
    
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Accepting/p/11235207.html
今日推荐