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 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).
For each case, print the case number and the minimum number of transformations needed. If it's impossible, then print -1.
2
6 12
6 13
Case 1: 2
Case 2: -1
题意:给两个数s, t,用s加上它的素因子(不包括1和它自身)得到另外一个数,然后重复之前的操作,加上当前数的素因子。。。直到得到t为止,问最少经过多少次的得到t
思路:迪杰斯特拉算法,,,,看了半天才想出来 bfs -_-|
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 1100;
const int INF = 0x3f3f3f3f;
int res, cas = 0;
int dis[N];
int pri[N];
void prime()
{
memset(pri, 0, sizeof pri);
for(int i = 2; i * i < N; i++)
if(pri[i] == 0)
for(int j = i * 2; j < N; j += i)
pri[j] = 1;
}
void bfs(int a, int b)
{
queue<int> que;
memset(dis, 0x3f, sizeof dis);
que.push(a);
dis[a] = 0;
while(! que.empty())
{
int v = que.front();
que.pop();
if(v == b) return;
for(int i = 2; i < v; i++)
if(v % i == 0 && pri[i] == 0)
{
if(v + i > b) break; //不加这条的话,v + i的值可能会超过打好的素数表,导致错误
if(dis[v+i] > dis[v] + 1)
dis[v+i] = dis[v] + 1, que.push(v + i);
}
}
}
int main()
{
int t, a, b;
prime();
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &a, &b);
bfs(a, b);
if(dis[b] != INF)
printf("Case %d: %d\n", ++cas, dis[b]);
else printf("Case %d: %d\n", ++cas, -1);
}
return 0;
}