【LightOJ 1141 - Number Transformation】+ BFS

1141 - Number Transformation
PDF (English) Statistics Forum
Time Limit: 2 second(s) Memory Limit: 32 MB
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
Output for Sample Input
2
6 12
6 13
Case 1: 2
Case 2: -1

题意 : A 可以通过 + A 非本身的质因子,成为 B ,给出 s 和 t,判断 s 是否可以转换成 t

思路 : 预先统计出1~1e3每个数的质因子,如果 s == t,自然是一,如果s 和 t 其中一个是 质数者必定为 -1,其他 BFS

AC代码:

#include<cstdio>
#include<queue>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX = 1e3 + 10;
const int INF = 0x3f3f3f3f / 2;
typedef long long LL;
int p[MAX],vis[MAX],s,t,ok,cut;
vector <int> v[MAX];
struct node{
    int x,pl;
};
void init(){ // 查找每个数的质因子
    p[1] = 1;
    for(int i = 2; i < MAX; i++)
        for(int j = i + i; j < MAX; j += i)
            p[j] = 1;
    for(int i = 2; i < MAX; i++)
        for(int j = 2; j < i; j++)
            if(i % j == 0 && !p[j])
                v[i].push_back(j);
}
void bfs(){
    memset(vis,0,sizeof(vis));
    queue <node> q;
    vis[s] = 1;
    node o;
    o.x = s,o.pl = 0;
    q.push(o);
    while(!q.empty()){
        o = q.front();
        q.pop();
        if(o.x == t){
            ok = 1,cut = min(cut,o.pl);
            continue;
        }
        for(int i = 0; i < v[o.x].size(); i++){
            node w;
            w.x = o.x + v[o.x][i],w.pl = o.pl + 1;
            if(w.x <= t && !vis[w.x]) vis[w.x] = 1,q.push(w);
        }
    }
}
int main()
{
    init();
    int T,nl = 0;
    scanf("%d",&T);
    while(T--){
        scanf("%d %d",&s,&t);
        if(s == t) printf("Case %d: 0\n",++nl);
        else if(!p[s] || !p[t]) printf("Case %d: -1\n",++nl);
        else{
            ok = 0,cut = INF;
            bfs();
            if(ok) printf("Case %d: %d\n",++nl,cut);
            else printf("Case %d: -1\n",++nl);
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值