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 @ 2023-06-16 22:40  风乐  阅读(13)  评论(0)    收藏  举报