Number Transformation

来源:互联网 发布:http 服务器默认端口 编辑:程序博客网 时间:2024/05/21 23:53

n 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

要注意到这道题下一次加质因数是在第一次的基础之上,如输入 6  12;第一次6可以加3等于9,加2等于8,第二次就变成9加3等于12或者8加2等于10,以此类推

一开始没有理解好队列的处理,后来看懂了,就是每次取出加的一个质因子在对这个质因子进行处理,下一次在处理下一个质因子,以此类推。

#include<cstdio>#include<queue>#include<vector>#include<cstring>#include<algorithm>using namespace std;const int MAX = 1e3 + 10;const int INF = 0x3f3f3f3f / 2;typedef long long LL;int p[MAX],vis[MAX],s,t,ok,cut;vector <int> v[MAX];struct node{    int x,pl;};void init(){ // 查找每个数的质因子,但此题不加上本身     p[1] = 1;    for(int i = 2; i < MAX; i++)        for(int j = i + i; j < MAX; j += i)            p[j] = 1;    for(int i = 2; i < MAX; i++)          for(int j = 2; j < i; j++)            if(i % j == 0 && !p[j])                v[i].push_back(j);  // 把每个数的质因子存到v[i]中 }void bfs(){    memset(vis,0,sizeof(vis));    queue <node> q;    vis[s] = 1;    node o;    o.x = s,o.pl = 0;    q.push(o);    while(!q.empty()){        o = q.front();//先把存入队列中第一个数的数赋给0         q.pop();//这个数清掉         if(o.x == t){            ok = 1,cut = min(cut,o.pl);//比较路径较少的一个             continue;        }        for(int i = 0; i < v[o.x].size(); i++){            node w;            w.x = o.x + v[o.x][i],w.pl = o.pl + 1;            if(w.x <= t && !vis[w.x]) vis[w.x] = 1,q.push(w);        }    }}int main(){    init();     int T,nl = 0;    scanf("%d",&T);    while(T--){        scanf("%d %d",&s,&t);        if(s == t) printf("Case %d: 0\n",++nl);        else if(!p[s] || !p[t]) printf("Case %d: -1\n",++nl);        else{            ok = 0,cut = INF;            bfs();            if(ok) printf("Case %d: %d\n",++nl,cut);            else printf("Case %d: -1\n",++nl);        }    }    return 0;}