LightOJ - 1141 Number Transformation ——————BFS+素因子分解

本文介绍了一种基于质因数变换的算法,旨在解决从一个整数通过加法操作转换为另一个整数的问题,其中加法操作的数值必须是当前整数的质因数之一。文章详细描述了算法的实现过程,包括初始化质因数、使用优先队列进行广度优先搜索,并最终找到最少变换次数的解决方案。

**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 s to 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


要注意A是不断变化的,所以它的质因子也会变化
还有啊注意A的质因子不能有1,A


#include<bits/stdc++.h>
using namespace std;
int s,t,ans;
int cnt;
int num,T;
int p[1000];
bool vis[3000];

struct node {
    int x,step;
    node(){};
    node(int _x,int _step)
    {
        x=_x; step=_step;
    }
    bool operator < (const node &b)const
    {
        return step>b.step;
    }
};

void init(int n)
{
    memset(p,0,sizeof(p));
    cnt=0;
    int z=n;
    for(int i=2;i*i<=n;i++)
    {
        if(n%i==0)
        {
            p[cnt++]=i;
            while(n%i==0)  n/=i;
        }
    }
    if(n!=1&&n!=z)    p[cnt++]=n;
}

void bfs(int s,int t)
{
    memset(vis,0,sizeof(vis));
    priority_queue<node> que;
    node e1,e2;
    que.push(node(s,0));
    vis[s]=1;
    while(que.size())
    {
        e1=que.top();que.pop();
        if(e1.x==t)
        {
            ans=e1.step;
            break;
        }
        init(e1.x);
        for(int i=0;i<cnt;i++)
        {
            e2.x = e1.x + p[i];
            e2.step = e1.step + 1;
            if(!vis[e2.x] && e2.x <= t)
            {
                vis[e2.x]=1;
                if(e2.x==t)
                {
                    ans=e2.step;
                    break;
                }
                que.push(e2);
            }
        }
    }
}
int main()
{

    scanf("%d",&num);
    T=num;
    while(num--)
    {
        scanf("%d %d",&s,&t);
        ans=-1;
        bfs(s,t);
        printf("Case %d: %d\n",T-num,ans);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值