POJ 3278 Catch That Cow BFS

题意:John的奶牛丢失了,现在有人告诉他奶牛的位置为e, 而他自己的位置为s,e与s在同一条直线上。现在John去追赶他的奶牛,他又两种方式可以选择。
1. 在任意位置 x 可以走到 x-1 或者 x + 1, 耗时一分钟
2. 在任意位置 x 可以走到 x * 2, 耗时一分钟。
求出John追上奶牛所需的最少时间。
题解:说明一下。一开始我将数组开到200000,用来计算跳出100000之后又返回的情况。其实这完全没有必要。因为如果某一路径途中大于100000,那么一定存在另一条路径不会经过大于100000的点,且后一路径所花时间小于等于前一路径。举个简单的例子。从60000-120000-100000 > 60000-50000-100000


#include <queue>
#include <iostream>
using namespace std;

int s, e;
int step[100001], check[100001];

int bfs ()
{
	queue<int> Q;
	Q.push ( s );
	step[s] = 0;
	check[s] = 1;
	int cur, next;
	while ( ! Q.empty () )
	{
		cur = Q.front ();
		Q.pop();
		if ( cur == e )
			return step[cur];
		next = cur - 1;
		if ( next >= 0 && next < 100001 && ! check[next] )
		{
			check[next] = 1;
			step[next] = step[cur] + 1;
			Q.push ( next );
		}
		next = cur + 1;
		if ( next >= 0 && next < 100001 && ! check[next] )
		{
			check[next] = 1;
			step[next] = step[cur] + 1;
			Q.push ( next );
		}
		next = cur * 2;
		if ( next >= 0 && next < 100001 && !check[next] )
		{
			check[next] = 1;
			step[next] = step[cur] + 1;
			Q.push ( next );
		}
	}
	return 0;
}

int main()
{
	while ( scanf("%d%d",&s,&e) != EOF )
	{
		memset(check,0,sizeof(check));
		printf("%d\n", bfs());
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值