1100. 抓住那头牛(bfs)

https://www.acwing.com/problem/content/1102/

数据范围为1e5

实际上还可以再继续细分,加入特判来优化耗时,但是意义不大

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

using namespace std;


const int N = 1e5+10;

int n,k;
bool vis[N];
int res[N];
int d1[3]={-1,1,2};

void bfs(int start)
{
	queue<int>q;
	q.push(start);
	vis[start]=true;
	while(q.size())
	{
		int t=q.front();
		q.pop();
		for(int i=0;i<3;i++)
		{
			int now;
			if(i==2)now=t*2;
			else now=t+d1[i];
			if(now >=0 && now <= N && !vis[now])
			{
				q.push(now);
				vis[now]=true;
				res[now]=res[t]+1;
			}	
		}
		if(t==k)return;
	}
}

int main()
{
	cin >> n >> k;
	
//	if(n>=k)//这里可以加一个特判
//	{
//		cout << n-k << endl;
//		return 0;
//	}
	bfs(n);
	
	cout << res[k] << endl;
}

 

posted @   风乐  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
点击右上角即可分享
微信分享提示