POJ-3278

#include
#include
#include

using namespace std;
struct node {
	int n;
	int step;
};

int  BFS(int start,int end) {
	queue q;
	node S;
	S.n = start;
	S.step = 0;
	q.push(S);
	while (!q.empty()) {
		node now = q.front();
		node next0, next1, next2;
		q.pop();
		if (now.n == end) {
			return now.step;
		}
		else {
			next0.n = now.n + 1;
			next1.n = now.n - 1;
			next2.n = now.n * 2;
			next0.step = now.step + 1;
			next1.step = now.step + 1;
			next2.step = now.step + 1;
			q.push(next0);
			q.push(next1);
			q.push(next2);
		}
	}
}

int main() {
	int n = 5, m = 17;
	int steo = BFS(5, 17);
	cout << steo;
	return 0;
}
#include
#include
#include

using namespace std;
const int maxz = 10001;
int step[maxz], vis[maxz];
int n, m;

int  BFS(int start,int end) {
	queue q;
	vis[n] = 1;
	step[n] = 0;
	q.push(start);
	while (!q.empty()) {
		int now = q.front();
		int next;
		q.pop();
		for (int i = 0; i < 3; i++) {
			if (i == 0) next = now - 1;
			if (i == 1) next = now + 1;
			if (i == 2) next = now * 2;

			if (next<0 || next>maxz) continue;

			if (!vis[next]) {
				vis[next] = 1;
				q.push(next);
				step[next] = step[now] + 1;
			}
			if (next == end)
				return step[next];
				
		}
	}
}

int main() {

	memset(vis, 0, sizeof(vis));
	cin >> n>>m;
	if (n > m)
		cout <<( n - m);
	else {
		cout << BFS(n, m);
	}
	
	return 0;
}

 

你可能感兴趣的:(C++,kuangbin带你飞)