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
题意:献给一个T,表示有T组数据,然后又给两个数s,t;s经过加素因数变成c(素因数是指1~c内的因子(这些必须是素数)),问最少需要加几次。不能加到t时输出-1.
题解:这是一道简单的广搜题,但是首先需要素数打表(否则会时间超限)。
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int n,m,flag,ss[1100],book[1100];
void sushu()
{
memset(ss,0,sizeof(ss));
for(int i=2;i<1100;i++)
{
if(ss[i]==0)
{
for(int j=i*2;j<1100;j+=i)
ss[j]=1;
}
}
}
struct node
{
int x,f;
};
void bfs(int x1)
{
queue<node>q;
node a,b;
a.x=x1;
a.f=0;
book[x1]=1;
while(!q.empty())
q.pop();
q.push(a);
while(!q.empty())
{
a=q.front();
q.pop();
for(int i=2;i<a.x;i++)
{
if(a.x%i==0&&ss[i]==0)
{
b.x=a.x+i;
if(book[b.x]==1||b.x>m)
continue;
book[b.x]=1;
b.f=a.f+1;
if(b.x==m)
{
flag=b.f;
return ;
}
q.push(b);
}
}
}
return ;
}
int main()
{
int T,k=1;
scanf("%d",&T);
sushu();
while(T--)
{
flag=0;
memset(book,0,sizeof(book));
scanf("%d%d",&n,&m);
if(n==m)
printf("Case %d: 0\n",k++);
else
{
bfs(n);
if(flag==0)
printf("Case %d: -1\n",k++);
else
printf("Case %d: %d\n",k++,flag);
}
}
return 0;
}