LightOJ - 1141【bfs+分解质因子】

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
题意:
在这个问题中,给出一个整数s。 您可以将任何整数A转换为另一个整数B,将x添加到A.这个x是一个整数,它是A的素因子(请注意,1和A不被视为A的因子)。 现在,您的任务是找到将s转换为另一整数t所需的最小转换次数。(谷歌版)
思路:
普通队列就可以,没必要优先,主要是每次转换后的B就是下一个A,题意明确点,接下来就是搜了;

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define INF 0x3f3f3f3f
using namespace std;
int vis[1010],p[1010];
int s,t,cnt,ans;

struct node
{
    int x;
    int step;
    bool friend operator<(node a,node b)
    {
        return a.step>b.step;
    }
};

void getp(int n)
{
    cnt=0;
    int m=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!=m) p[cnt++]=n;
}

void bfs()
{
    bool flag=false;
    priority_queue<node> q;
    node now,next;
    now.x=s;
    vis[s]=1;
    now.step=0;
    q.push(now);
    while(!q.empty())
    {
        next=q.top();
        q.pop();
        if(next.x==t)
        {
            ans=min(ans,next.step);
            flag=true;
            continue;
        }
        memset(p,0,sizeof(p));
        getp(next.x); 
        for(int i=0;i<cnt;i++)
        {
            now.x=next.x+p[i];
            now.step=next.step+1;
            if(now.x<=t && !vis[now.x])
            {
                vis[now.x]=1;
                q.push(now);
            }
        }
    }
    if(flag) printf("%d\n",ans);
    else printf("-1\n");
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        static int res=1;
        ans=INF;
        memset(vis,0,sizeof(vis));
        scanf("%d %d",&s,&t);
        printf("Case %d: ",res++);
        if(s==t)
        {
            printf("0\n");
            continue;
        }
        if(s>t)
        {
            printf("-1\n");
            continue;
        }
        bfs();
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值