poj 3278

#include<iostream>
#include<queue>
#include<cstring>
#include<queue>

using namespace std;
int n, k;
int step[100010];
int vis[100010];
queue<int> q;

int bfs(int n) {
	q.push(n);
	step[n] = 0;
	vis[n] = 1;
	int head, next;
	while(!q.empty()) {
		int i;
		head = q.front();
		q.pop(); 
		for(i = 0; i < 3; i++) {
			if(i == 0) next = head + 1; //三个方向 
			else if(i == 1) next = head - 1;
			else next = head * 2;
			if(next >= 100010 || next < 0) continue; //防止越界 
			if(!vis[next]) {  //标记了之后下次再走这里一定比上次用的步数多 
				q.push(next);
				step[next] = step[head] + 1;
				vis[next] = 1;
			}
			if(next == k) return step[next];
		}
	}
}

int main() {
	cin >> n >> k;
	if(k <= n) {
		cout << n - k << endl;
	}
	else {
		cout << bfs(n) << endl;
	}
	return 0;
}

你可能感兴趣的:(poj 3278)