今天呢我们再来做一道稍微难一点的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
Case 1: 2
Case 2: -1
这个题的大概意思就是说,让你从s变成t需要几步,怎么个变法呢?就是s可以加上他的素数因子,然后变成的这个数重复这个过程,接着加起其自己的素数因子,依次往下推,直到变成那个数字,如果变成不了那个数字,那么就输出-1;
读完题后,我们可以很明显的看出这是一道典型的BFS的题,只要依次往下搜就行了,突然感觉现在对BFS的理解又加深了一步,相比于刚那开始学的时候啥都不知道,自己真的进步了好多,看来学习真的是一个循环渐进的过程,不管你去学习什么,思路都是一样的,不要急,不要急于求成,慢慢来,你自己都不知道你进步有多大。
这题刚开始写好后怎么运行都不对,后来慢慢的调试,才发现自己写了好多的bug,唉,可能还是不太熟练吧,再多做几道可能就好了,
好了废话少说,下面给出AC代码;
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
const int maxn=1007;
int b[maxn];
int su[maxn];
int s,q;
int C=0;
struct stu
{
int date;
int step;
}A,B;
void S()
{
memset(su,0,sizeof(su));
su[0]=1;
su[1]=1;
for(int i=2;i<=maxn;i++)
{
if(!su[i])
{
for(int j=i*i;j<=maxn;j+=i)
su[j]=1;
}
}
}
void bfs(int n)
{
queue<stu> que;
A.date=n;
A.step=0;
int cnt=-1;
b[n]=1;
que.push(A);
while(!que.empty())
{
A=que.front();
que.pop();
if(A.date==q)
{
cnt=A.step;
break;
}
for(int i=2;i<A.date;i++)
{
if(A.date%i==0&&b[A.date+i]==0&&su[i]==0&&A.date+i<=q)
{
B.step=A.step+1;
B.date=A.date+i;
b[B.date]=1;
que.push(B);
}
}
}
printf("Case %d: %d\n",C,cnt);
}
int main()
{
int t;
scanf("%d",&t);
S();
while(t--)
{
C++;
memset(b,0,sizeof(b));
scanf("%d %d",&s,&q);
bfs(s);
}
return 0;
}