In this problem, you are given an integer number s. You can transform any integer number A to another integer numberB 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 sto 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).

 
OutputFor 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和本身外的质因数,分别相加得到几个数,就转化了几次,然后得到的数重复以上操作,直到.....)

#include<stdio.h>
#include<queue>
using namespace std;
#include<string.h>
int c[1010],vis[1010];
int a,b,f;
struct note
{
    int x,s;
};
int prime(int n)
{
    if(n<2)return 0;
    for(int i=2; i<n; i++)
    {
        if(n%i==0)return 0;
    }
    return 1;
}
void bfs(int x)
{
    queue<note>Q;
    note p,q;
    p.x=x;
    p.s=0;
    vis[x]=1;//标记用过的数字防止循环
    Q.push(p);
    while(!Q.empty())
    {
        p=Q.front();
        Q.pop();
        if(p.x==b)
        {
            f=p.s;
            break;//找到后跳出循环,return的作用不清楚为什么不能用呢
        }
        for(int i=2; i<p.x; i++)//新的数在其范围内找质 !因! 数! ,
                    //并且判断是否大于t,或者加上质因数后得到一个用过的数
        {
            if(c[i]==0||p.x+i>b||p.x%i!=0||vis[p.x+i])continue;
            q.x=p.x+i;
            vis[q.x]=1;
            q.s=p.s+1;
            Q.push(q);
        }
    }
    return;
}
int main()
{
    int k=0,flag=0;
    for(int i=2; i<=1005; i++)
    {
        c[i]=prime(i);
    }
    int t;
    scanf("%d",&t);
    while(t--)
    {
        f=-1;
        memset(vis,0,sizeof(vis));
        scanf("%d%d",&a,&b);
        bfs(a);
        printf("Case %d: %d\n",++flag,f);
    }
    return 0;
}


posted on 2017-07-13 16:57  zitian246  阅读(109)  评论(0编辑  收藏  举报