抓住那头牛 —一维BFS—坐标移动

  •  

  • 输入格式

    共一行,包含两个整数N和K。

    输出格式

    输出一个整数,表示抓到牛所花费的最少时间。

    数据范围

    0≤N,K≤1e5

    输入样例:

    5 17
    

    输出样例:

    4
    

分析: 注意适当剪枝!不然会超内存

法一:使用pair——40 ms

#include <bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
const int N = 1e7 + 10;
typedef pair<int, int>pii;
int st, ed;
bool vis[N]; 
void bfs() {
	queue<pii>q;
	q.push(make_pair(st, 0));//起始位置和step;
	vis[st] = true;
	while (q.size()) {
		int now = q.front().first;
		int step = q.front().second;
		q.pop();
		if (now == ed) {
			cout << step << endl;
			return;
		}
		if (now + 1 <= ed && !vis[now+1]) {
			vis[now+1] = true;
			q.push({ now+1,step + 1 });
		}
		if (now-1>=0&& !vis[now-1]) {
			vis[now-1] = true;
			q.push({ now-1,step + 1 });
		}
		if (now <= ed &&!vis[now*2]) {
			vis[now*2] = true;
			q.push({ now*2,step + 1 });
		}
	}
	cout << "no" << endl;
}
signed main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	cin >> st >> ed;
	bfs();
	return 0;
}

 法二:开dis数组存放步数——105ms,比pair慢

#include <iostream>
#include <cstring>
#include <queue>

using namespace std;

const int N=2e5+10;

int n,k,dist[N];


int bfs()
{
    memset(dist,-1,sizeof dist);
    
    queue<int> q;
    q.push(n);
    dist[n]=0;
    
    while(q.size())
    {
        int t=q.front();
        q.pop();
        
        if(t==k) return dist[k];
        
        if(t+1<N&&dist[t+1]==-1)
        {
            dist[t+1]=dist[t]+1;
            q.push(t+1);
        }
        
        if(t-1>=0&&dist[t-1]==-1)
        {

            dist[t-1]=dist[t]+1;
            q.push(t-1);
        }
        
        if(2*t<N&&dist[2*t]==-1)
        {
            dist[2*t]=dist[t]+1;
            q.push(2*t);
        }
    }
    
    return -1;
}

int main()
{
    cin>>n>>k;
    
    cout<<bfs()<<endl;
    
    return 0;
}

这种写法很方便

	while (q.size()) {
		int now = q.front().first;
		int step = q.front().second;
		q.pop();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ou_fan

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

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

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

打赏作者

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

抵扣说明:

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

余额充值