POJ - 3278 - Catch That Cow (BFS)

25 篇文章 0 订阅


题目传送:Catch That Cow


思路:BFS找最小步数,用一个结构体存下当前结点的数值以及当前步数


AC代码:

#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <deque>
#include <cctype>
#define LL long long
#define INF 0x7fffffff
using namespace std;

int n, k;

bool vis[200005];

struct node {
	int num;
	int cnt;
	node(int n, int c) : num(n), cnt(c) {};
};

int bfs(int n, int k) {
	if(n == k) return 0;
	memset(vis, false, sizeof(vis));
	queue<node> que;
	que.push(node(n, 0));
	vis[n] = true;
	while(!que.empty()) {
		node t = que.front();
		que.pop();
		node n1 = node(t.num - 1, t.cnt + 1);
		node n2 = node(t.num + 1, t.cnt + 1);
		node n3 = node(t.num * 2, t.cnt + 1);
		if(n1.num == k) return n1.cnt;
		if(n2.num == k) return n2.cnt;
		if(n3.num == k) return n3.cnt;
		if(n1.num >= 0 && n1.num <= 150005 && !vis[n1.num]) {
			//重要剪枝,num小于0的时候肯定不是正解,还有num大于150000时肯定也不是正解 
			que.push(n1);
			vis[n1.num] = true;//入队列的时候就要赋值为已经访问过,不然会超时! 
		}
		if(n2.num >= 0 && n2.num <= 150005 && !vis[n2.num]) {
			que.push(n2);
			vis[n2.num] = true;
		}
		if(n3.num >= 0 && n3.num <= 150005 && !vis[n3.num]) {
			que.push(n3);
			vis[n3.num] = true;
		}
	}
}

int main() {
	while(scanf("%d %d", &n, &k) != EOF) {
		printf("%d\n", bfs(n, k)); 
	}
	return 0;
}








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值