0
点赞
收藏
分享

微信扫一扫

Catch That Cow POJ 3278 (BFS问题)

豆丁趣 2022-02-19 阅读 155

问题链接
http://poj.org/problem?id=3278
摘自王道笔试指南
在这里插入图片描述

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

const int MAXN = 100001;
vector<bool> inq(MAXN, false);

struct Status
{
	int loc;
	int time;
	Status() { }
	Status(int _loc, int _time) : loc(_loc), time(_time) { }
};

int BFS(int n, int k) {
	queue<Status> que;
	que.push(Status(n, 0));
	inq[n] = true;
	while (!que.empty()) {
		Status p = que.front();
		que.pop();
		if (p.loc == k) {
			return p.time;
		}
		for (int i = 0; i < 3; i++) {
			Status next;
			if (i == 0) {
				next.loc = p.loc - 1;
			}
			else if (i == 1) {
				next.loc = p.loc + 1;
			}
			else {
				next.loc = p.loc * 2;
			}
			next.time = p.time + 1;
			if (next.loc < 0 || next.loc >= MAXN || inq[next.loc]) {
				continue;
			}
			que.push(next);
			inq[next.loc] = true;
		}
	}
	return -1;
}

int main()
{
	int n, k;
	cin >> n >> k;
	int t = BFS(n, k);
	cout << t << endl;
	return 0;
}
举报

相关推荐

0 条评论