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,问s加上他自己的质因数至少加多少次等于t,题目中还有一个地方要特别注意A+X(为A的质因数)=B,这时候B也就变成下一步计算的A,把这一步搞明白了,这道题也就好些了。
#include<algorithm>
#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
#define INF 0x3f3f3f3f
using namespace std;
struct node{
int x,step;
bool friend operator <(node a,node b){
return a.step>b.step;
}
};
bool vis[10010];
int p[10010];
int s,t,k,ans;
void divide(int n){
k=0;
int m=n;
for(int i=2;i*i<=n;i++){
if(n%i==0){
p[++k]=i;
while(n%i==0) n=n/i;
}
}
if(n>1&&m!=n) p[++k]=n;//这里要注意考虑m!=n的情况,之前没注意到这个WA了好多次
}
void BFS(){
priority_queue<node> qu;
node e1;
e1.x=s,e1.step=0;
vis[s]=1;
qu.push(e1);
//int ans=INF;
bool flag=false;
while(!qu.empty()){
e1=qu.top();qu.pop();
node e2;
if(e1.x==t){
flag=true;
ans=min(ans,e1.step);
continue;
}
memset(p,0,sizeof(p));
divide(e1.x);//注意每次转换后的b就是下一个a
for(int i=1;i<=k;i++){
e2.x=e1.x+p[i];
e2.step=e1.step+1;
if(e2.x<=t&&!vis[e2.x]){
vis[e2.x]=1;
qu.push(e2);
}
}
}
if(flag) printf("%d\n",ans);
else printf("-1\n");
}
int main(){
int n,kase=0;
scanf("%d",&n);
while(n--){
ans=INF;
memset(vis,0,sizeof(vis));
scanf("%d %d",&s,&t);
printf("Case %d: ",++kase);
if(s==t){
printf("0\n");
continue;
}
if(s>t) {
printf("-1\n");
continue;
}
BFS();
}
return 0;
}