Number Transformation
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 sto 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
思路:题意就不用说了,毕竟这么简单
这道题解题思路其实很简单,素数打一下表,之后直接bfs暴搜即可(注意其中s是动态变化的,并且它的素因子也是动态变化的)
代码:(代码写的有点长,不过其实并不难写,主要是几个函数都要写一下)
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<map>
#include<set>
#include<vector>
#include<string>
#include<cstring>
#include<stack>
#include<queue>
#define ll long long
using namespace std;
bool check[105];
int prime[100];
int pos = 0,cnt,kase = 0;
bool vis[1005];
int factor[1005];
void init()
{
memset(check,0,sizeof(check));
for (int i = 2;i<= 100;i ++)
if (!check[i])
{
prime[pos ++] = i;
for (int j = i * 2;j <= 100;j += i)
check[j] = 1;
}
}
void solve(int a)
{
cnt = 0;
int m = a;
for (int i = 0;prime[i] * prime[i] <= a;i ++)
{
if (a % prime[i] == 0)
{
while (a % prime[i] == 0) a /= prime[i];
factor[cnt ++] = prime[i];
}
}
if (a != 1 && m != a) factor[cnt ++] = a;
}
struct node
{
int x,step;
friend bool operator < (node a,node b)
{
return a.step > b.step;
}
};
void bfs(int a,int b)
{
int ans = -1;
memset(vis,0,sizeof(vis));
priority_queue<node> que;
node p,p2;
p.x = a,p.step = 0;
vis[a] = 1;
que.push(p);
while (!que.empty())
{
p = que.top();
que.pop();
solve(p.x);
if (p.x == b)
{
ans = p.step;
continue;
}
p2 = p;
for (int i = 0;i < cnt;i ++)
{
p2.x = p.x + factor[i];
if (p2.x > b || vis[p2.x]) continue;
p2.step = p.step + 1;
que.push(p2);
vis[p2.x] = 1;
}
}
printf("Case %d: %d\n",kase,ans);
}
int main()
{
init();
int t,a,b;
scanf("%d",&t);
while (t --)
{
kase ++;
scanf("%d %d",&a,&b);
if (!check[a])
{
if (a == b)
printf("Case %d: 0\n",kase);
else
printf("Case %d: -1\n",kase);
continue;
}
if (a > b)
{
printf("Case %d: -1\n",kase);
continue;
}
bfs(a,b);
}
return 0;
}