Catch That Cow(队列)

  题目  ;http://acm.hdu.edu.cn/showproblem.php?pid=2717

#include <iostream>
#include <cstring>
#include<cstdio>
#include <stack>
#include <queue>
#include <map>
#include <algorithm>
using namespace std;
int vis[100001];
int n, m;
int ans;
struct node {
	int x, step;
};
int bfs() {
	queue<node>q;
	while (!q.empty()) {
		q.pop();
	}
	node now, next;
	now.x = n;
	now.step = 0;
	vis[now.x] = 1;
	q.push(now);
	while (!q.empty()) {
		now = q.front();
		q.pop();
		for (int i = 0; i < 3; i++) {
			if (i == 0) {
				next.x = now.x - 1;
			}
			else if (i == 1) {
				next.x = now.x + 1;
			}
			else if (i == 2) {
				next.x = now.x * 2;
			}
			next.step = now.step + 1;
			if (next.x == m) {
				return next.step;
			}
			if (!vis[next.x] && next.x >= 0 && next.x <= 100001) {
				q.push(next);
				vis[next.x] = 1;
			}
		}
	}
}
int main() {
	cin >> n >> m;
	memset(vis, 0, sizeof(vis));
	if (n >= m) {
		cout << n - m << endl;
	}
	cout << bfs() << endl;
}

猜你喜欢

转载自blog.csdn.net/yihanyifan/article/details/81197930