poj3278-bfs

题意大概是给你两个数N,K,让你一次次通过三种方式:N+1,N-1,N*2中的一种使得最终N==K,求出N到K的最小次数。
用vis数组判断是否被访问过,cnt数组保存步数。

#include <iostream>
#include <queue>

using namespace std;
int a, b;
queue <int> q;
int vis[100003], cnt[100003];
void init() {
	memset(vis, 0, sizeof(vis));
	memset(cnt, 0, sizeof(cnt));
}
int bfs() {
	int cur, next;
	cnt[a] = 0;
	vis[a] = 1;
	q.push(a);
	cur = a;
	while (!q.empty()) {
		cur = q.front();
		q.pop();
		int i;
		for (i = 0; i < 3; i++) {
			if (i == 0) {
				next = cur - 1;
			}
			else if (i == 1){
				next = cur + 1;
			}
			else {
				next = cur * 2;
			}
			if (next < 0 || next >= 100003)
				continue;
			if (!vis[next]) {
				q.push(next);
				cnt[next] = cnt[cur] + 1;
				vis[next] = 1;
			}
			if (next == b)
				return cnt[next];
		}
	}
	return -1;
}
int main() {
	scanf_s("%d%d", &a, &b);
	init();
	if (a >= b)
		printf("%d\n",a-b);
	else  
	        printf("%d\n",bfs());
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值