POJ Catch That Cow

题面

 

思路

 bfs模拟最短路,需要一个额外的数组保存这个点是否走过,搜索到这个点就跳出

#pragma GCC optimize(2)
#include<iostream>
#include<algorithm>
#include<queue>
typedef long long ll;
using namespace std;
struct yuu{
	int whw;
	int time;
};\\定义队列元素类型
queue<struct yuu> quu;
bool vis[100009];\\标记是否走过
int lef,cow,MIN;
void bfs(int wh,int tim)
{
	if(wh<0||wh>100000||vis[wh]==true)\\超界退出
	return ;
	if(wh==cow)\\搜索到就标记
	{
		vis[wh]=true;
		MIN=tim;
		return;
	}
	vis[wh]=true;\\标记并且入队
	struct yuu dd;
	dd.whw=wh,dd.time=tim;
	quu.push(dd);
}
int main()
{
	std::ios::sync_with_stdio(false);
    std::cin.tie(0);
	cin>>lef>>cow;
	struct yuu bb;
	bb.time=0,bb.whw=lef;
	vis[lef]=true;\\初始位置默认走过
	quu.push(bb);
	while(!quu.empty())
	{
		bb=quu.front();
		bfs(bb.whw-1,bb.time+1);
		bfs(bb.whw+1,bb.time+1);
		bfs(bb.whw*2,bb.time+1);
		quu.pop();
	}
	cout<<MIN<<endl;
	return 0;
}

  

posted on 2022-03-30 19:38  zesure  阅读(39)  评论(0)    收藏  举报

导航