POJ-3278

#include<iostream>
#include<string>
#include<queue>

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

int  BFS(int start,int end) {
	queue<node> 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<iostream>
#include<string>
#include<queue>

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

int  BFS(int start,int end) {
	queue<int> 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值