Catch That Cow(bfs)(注意边界条件)

Problem Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately.

农民J 被告知 fugitive牛的定位,并且想立马逮到他!

He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line.

他在一个点N上开始走,牛在K上,

Farmer John has two modes of transportation: walking and teleporting.

交通:走/电运
* Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute

走路:一分钟走到 x-1 x+1
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.
电运:X走到 2X  一分钟
If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

多次时间抓到?

 

Input

Line 1: Two space-separated integers: N and K

 

Output

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

 

Sample Input

 

5 17

 

Sample Output

 
4

Hint

The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
#include <iostream>
#include <queue>
using namespace std;

typedef struct Now {
	int pos;
	int t;
} Now;

bool mark[100001];
queue<Now> q;

int bfs(int n,int k) {
	while(!q.empty()) {
		q.pop();
	}

	Now chu;
	chu.pos = n;
	chu.t = 0;

	Now father;
	Now child;

	q.push(chu);
	while(!q.empty()) {
		father = q.front();
		q.pop();


		if (father.pos + 1 >= 0 && father.pos + 1 <= 100000 && mark[father.pos + 1] == 0) {
			child = father;
			child.pos ++;
			child.t++;

			if (child.pos == k) {
				return child.t;
			}
			mark[child.pos] = 1;
			q.push(child);
		}

		if (father.pos - 1 >= 0 && father.pos - 1 <= 100000 && mark[father.pos - 1] == 0) {
			child = father;
			child.pos --;
			child.t++;
			if (child.pos == k) {
				return child.t;
			}
			mark[child.pos] = 1;
			q.push(child);
		}

		if (father.pos * 2 >= 0 && father.pos * 2 <= 100000 && mark[father.pos * 2] == 0) {
			child = father;
			child.pos *= 2;
			child.t++;
			if (child.pos == k) {
				return child.t;
			}
			mark[child.pos] = 1;
			q.push(child);
		}

	}

	return -1;

}


int main() {
	int n;
	int k;
	while (cin >> n >> k) {
		for (int i = 0; i <= 100000; i++) {
			mark[i] = 0;
		}
		if (n == k) {
			cout << 0 << endl;
		} else {

			int res = bfs(n,k);
			cout << res << endl;

		}

	}


}
发布了86 篇原创文章 · 获赞 0 · 访问量 3633

猜你喜欢

转载自blog.csdn.net/bijingrui/article/details/104762573