LightOJ 1141 Number Transformation bfs

题目:http://lightoj.com/volume_showproblem.php?problem=1141

题意:给两个数s, t,用s加上它的素因子(不包括1和它自身)得到另外一个数,然后重复之前的操作,加上当前数的素因子。。。直到得到t为止,问最少经过多少次的得到t

思路:刚开始用的dfs,T了,发现bfs可以轻松求解,然后就一直错错错!!!痛心-_-||。。。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
#include <set>
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;
}










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值