计蒜客--一维坐标的移动

题目如上,该题刚开始写bfs时,在一个while循环里面进行加减乘,然后内存超限,经过无数次的修改之后终于过题了。。

程序大体思想如下:先进行起点,终点的判断。如果起点大于终点或者起点等于终点,那么直接用起点减去终点。

接下来进行两次广搜。第一次广搜用于判断加和乘,第二次广搜用于判断减和乘。

代码如下:
 

#include <iostream>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;
int n,m;
struct Point
{
    int x,step;
    Point(int _x,int _step):
        x(_x),step(_step) {}
};
int main()
{
    int n,a,b;
    cin>>n>>a>>b;
    queue<Point>q;
    q.push(Point(a,0));
    if(a>b)
    {
        cout<<a-b<<endl;
        return 0;
    }
    if(a==b)
    {
        cout<<0<<endl;
        return 0;
    }
    int cnt = 0;
    while(!q.empty())
    {
        int x = q.front().x;
        int step = q.front().step;
        q.pop();

        if(x == b)
        {
            cnt = step;
            break;
        }
        if(x+1 <= n && a<b)
        {
            //cout<<1<<" "<<x<<endl;
            q.push(Point(x+1,step+1));
        }
        if(x*2 <=n && a<b)
        {
            //cout<<3<<endl;
            q.push(Point(x*2,step+1));
        }
    }
    //cout<<"cnt="<<cnt<<endl;
    while(!q.empty())
        q.pop();
    q.push(Point(a,0));
    while(!q.empty())
    {
        int x = q.front().x;
        int step = q.front().step;
        q.pop();
        //cout<<step<<endl;
        if(x == b)
        {
            if(cnt > step)
            {
                cnt = step;
            }
            break;
        }
        
        if(step > cnt)
            break;
        if(x-1 >=0)
        {
            q.push(Point(x-1,step+1));
        }
        if( x*2 == b )
        {
            q.push(Point(x*2,step+1));
        }
        if( x*2+1 == b )
        {
            q.push(Point(x*2+1,step+1));
        }
    }
    cout<<cnt<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九久呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值