Sample Input
2
6 12
6 13
Sample Output
Case 1: 2
Case 2: -1
思路
在这个问题中,给出一个整数s。 您可以通过将x添加到A来将任何整数A转换为另一个整数B.此x是整数,它是A的素数因子(请注意,1和A不被视为A的因子)。 现在,您的任务是找到将s转换为另一个整数t所需的最小转换次数。
注意:将A添加A的质因子(除了1和它本身外)变成B后,下一次再进行加x操作后,B就变成了原来的A。(理解这一步很重要)。
AC Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = (int)1e3+10;
int cnt;
int dp[35];
bool vis[MAXN];
struct node
{
int x, step;
friend bool operator < (node a, node b)
{
return a.step > b.step;
}
};
void solve(int n)
{
int w = n;
bool flag;
for(int i=2; i*i<=n; i++)
{
flag = false;
while(n%i==0)
{
if(!false)
{
flag = true;
dp[++cnt] = i;
}
n = n / i;
}
}
if(n!=1 && n!=w) dp[++cnt] = n;
}
void bfs(int s, int t)
{
int ans = 0;
if(s==t)
{
printf("%d\n",ans);
return ;
}
else if(s>t)
{
printf("-1\n",ans);
return ;
}
memset(vis,false,sizeof(vis));
priority_queue<node> qu;
node st1, st2;
st1.x = s, st1.step = 0;
vis[st1.x] = true;
qu.push(st1);
while(!qu.empty())
{
st1 = qu.top();
qu.pop();
if(st1.x==t)
{
ans = st1.step;
break;
}
cnt = 0;
memset(dp,0,sizeof(dp));
solve(st1.x);
for(int i=1; i<=cnt; i++)
{
st2.x = st1.x + dp[i];
if(st2.x<=t && !vis[st2.x])
{
vis[st2.x] = true;
st2.step = st1.step + 1;
qu.push(st2);
}
}
}
if(ans!=0) cout<< ans << endl;
else printf("-1\n");
}
int main()
{
int T;
scanf("%d",&T);
for(int Case=1; Case<=T; Case++)
{
int s, t;
scanf("%d %d",&s,&t);
printf("Case %d: ",Case);
bfs(s,t);
}
return 0;
}