bfs(太空电梯)

http://oj.jxust.edu.cn/contest/problem?id=1563&pid=4

题目描述

公元9012年,Q博士发明了一部太空电梯,与一般电梯不同,太空电梯不能直接到达目点。太空电梯只有上升和下降两个按键,如果电梯上升,
它只能上升当前高度的距离;如果下降,它一次只能下降1米的距离。
为了使大家都能上太空去玩耍,Q博士想请你根据电梯的工作原理,计算到达目的点最少需要按几次按键

输入

多组输入

每组输入有两个数n和m(1<=n,m<=10^7),表示当前高度n和目的点m

输出

输出计算结果

样例输入

4 6
10 1
255 999999

样例输出

2
9
28
题意:电梯有两个按钮 , 一个是上升目前高度的按钮 , 另一个是下降1个高度的按钮。
如何从起始高度到达目标高度并要求求出按最少次按钮的次数。

我一开始想的是用dfs,我就去看了下分别在什么情况下使用dfs和bfs。
dfs特点:可以不重不漏的枚举所有可以到达目标状态的路径。(回溯思想 , 枚举思想)

bfs特点:效率较高,适合于找一条最快到达目标状态的路径。(发散思想)

 

//#include <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <stdio.h>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <string.h>
#include <vector>
#define ME(x , y) memset(x , y , sizeof(x))
#define SF(n) scanf("%d" , &n)
#define rep(i , n) for(int i = 0 ; i < n ; i ++)
#define INF  0x3f3f3f3f
#define mod 1000000007
using namespace std;
typedef long long ll ;
int n , m ;
int vis[100000009] , ans[100000009];

int bfs()
{
    queue<int>q;
    vis[n] = 1 ;
    q.push(n);
    if(m % 2 == 1)
    {
        m++ ;
        ans[m]++;
    }
    while(!q.empty())
    {
        int x = q.front();
        q.pop();
        if(x == m)
        {
            return ans[m];
        }
        if(x*2 <= m && !vis[x*2])
        {
            vis[2*x] = 1 ;
            ans[2*x] += ans[x] + 1 ;
            q.push(2*x);
        }
        if(x - 1 > 0 && !vis[x-1])
        {
            vis[x-1] = 1 ;
            ans[x-1] += ans[x] + 1 ;
            q.push(x-1);
        }
    }
}
int main()
{
    while(~scanf("%d%d" , &n ,&m))
    {
        memset(ans, 0 , sizeof(ans));
        memset(vis , 0 , sizeof(vis));
        if(n < m)
            cout << bfs() << endl ;
        else
        {
            cout << n - m << endl ;
        }
    }


    return 0 ;
}

 

刷题后感:标记查找过的点是bfs 和 dfs 的重要部分。






原文链接: https://www.cnblogs.com/nonames/p/q-bo-shi-de-dian-ti.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    bfs(太空电梯)

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/297071

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午6:23
下一篇 2023年2月15日 下午6:25

相关推荐