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 A are 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 |
6+3=9
8+2=10
9+3=12
10+2=12
10+5=15
12+2=14
12+3=15,其中12,15此时被最少搜索两次,后面还有可能再次搜到它们,要达到999很难,所以把这些状态要标记,避免重复搜索)。
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
int a,b,ans;
int su[1010];
int vis[1010];
vector<int> v[1010];
struct node
{
int num,step;
};
void dabiao()
{
su[0]=1;
su[1]=1;
for(int i=2;i<1010;i++)
{
if(su[i]==1)
{
continue;
}
for(int j=i*2;j<1010;j=j+i)
{
su[j]=1;
}
}
for(int i=0;i<1010;i++)
{
v[i].clear();
}
for(int i=0;i<1010;i++)
{
for(int j=2;j<i;j++)
{
if(su[j]==0&&i%j==0)
{
v[i].push_back(j);
}
}
}
}
void bfs()
{
memset(vis,0,sizeof(vis));
node x,y;
x.num=a;
x.step=0;
queue<node> q;
while(!q.empty())
{
q.pop();
}
q.push(x);
vis[a]=1;
while(!q.empty())
{
x=q.front();
q.pop();
if(x.num==b)
{
ans=x.step;
break;
}
for(int i=0;i<v[x.num].size();i++)
{
y.num=x.num+v[x.num][i];
if(y.num<=b&&vis[y.num]==0)
{
vis[y.num]=1;
y.step=x.step+1;
q.push(y);
}
}
}
}
int main()
{
dabiao();//素数打表+素因子打表
int t;
scanf("%d",&t);
int cnt=1;
while(t--)
{
scanf("%d%d",&a,&b);
ans=-1;//初始化结果
bfs();
printf("Case %d: %d\n",cnt++,ans);
}
return 0;
}