poj3278 Catch That Cow BFS

Catch That Cow
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 68679   Accepted: 21628

Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. 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. Farmer John has two modes of transportation: walking and teleporting.

* Walking: FJ can move from any point X to the points - 1 or + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

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.


最少步数,用BFS

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

using namespace std;

struct node {
	int n, c;
	node() {}
	node(int n, int c) : n(n), c(c) {}
};

int N, K, cou, minn;
//注意要标记已经走过的,不然广搜会爆内存!
//vis尽量开大一点,防止*2的时候爆了
bool vis[300005];
queue<node> Q;

void bfs() {
	while (!Q.empty()) Q.pop();  //初始化队列 
	
	Q.push(node(N, cou));  //第一个点入队列 
	vis[N] = true;
	
	cou = 0;
	while (!Q.empty()) {
		node tn = Q.front(); Q.pop();
		if (tn.n == K) {
			printf("%d\n", tn.c);
			return ;
		}
		//发现下一步可以的话直接打印结果返回 
		if (tn.n + 1 == K || tn.n - 1 == K || tn.n * 2 == K) {
			printf("%d\n", tn.c + 1);
			return ;
		}
		for (int i = 1; i <= 3; i++) {
			if (i == 1 && tn.n + 1 <= K && !vis[tn.n + 1]) {
				Q.push(node(tn.n + 1, tn.c + 1));
				vis[tn.n + 1] = true;
			} else if (i == 2 && tn.n * 2 < 300000 && !vis[tn.n * 2]) {
				Q.push(node(tn.n * 2, tn.c + 1));
				vis[tn.n * 2] = true;
			} else if (i == 3 && tn.n - 1 >= 1 && !vis[tn.n - 1]) {
				Q.push(node(tn.n - 1, tn.c + 1));
				vis[tn.n - 1] = true;
			}
		}
	}
}

int main()
{
	while (~scanf("%d%d", &N, &K)) {
		memset(vis, false, sizeof(vis));
		
		//因为如果刚开始的位置就比牛大的话
		//只能-1 
		if (N >= K) {
			printf("%d\n", N - K);
			continue;
		}
		bfs();
	}
	return 0;
}


你可能感兴趣的:(算法,搜索,ACM,poj,bfs)