Time Limit: 2 second(s) | Memory Limit: 32 MB |
In this problem, you are given an integer number s.You can transform any integer number A to another integer number Bby adding x to A. This x is an integer number which is aprime factor of A (please note that 1 and Aare not beingconsidered as a factor of A). Now, your task is to find the minimumnumber of transformations required to transform s to another integernumber 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 numberof transformations needed. If it's impossible, then print -1.
Sample Input | Output for Sample Input |
2 6 12 6 13 | Case 1: 2 Case 2: -1 |
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int c[1100][6]= {0},lu[1010],a,b;
struct yun
{
int x,s;
};
int bfs(int x)
{
yun st,en;
queue<yun>Q;
st.x=x;
st.s=0;
Q.push(st);
while(Q.size())
{
st=Q.front();
Q.pop();
for(int i=1; i<=5; i++)//1000以内的数的素因子最多不超多5个;
{
int dx=st.x+c[st.x][i];
if(lu[dx]||dx>b)continue;//判重,是否越界;
lu[dx]=1;//标记;
en.x=dx;
en.s=st.s+1;
if(en.x==b)
return en.s;
Q.push(en);
}
}
return -1;
}
int prime(int q)//
{
for(int i=2; i<q; i++)
if(q%i==0)return 0;
return 1;
}
int main()
{
int m,i,j,t,f=1;
c[1][1]=0;
c[2][1]=0;
for(i=3; i<=1000; i++)//从1到1000的数的素因子打表;
{
for(j=2,t=0; j<i; j++)
{
if(i%j==0&&prime(j))
{
c[i][++t]=j;
}
}
}
scanf("%d",&m);
while(m--)
{
scanf("%d%d",&a,&b);
memset(lu,0,sizeof(lu));
lu[a]=1;
if(a==b)printf("Case %d: 0\n",f++);
else
printf("Case %d: %d\n",f++,bfs(a));
}
}