HDU2717:Catch That Cow(BFS)

题目链接:https://vjudge.net/contest/214162#problem/C
解题报告:这是一题简单的搜索题,但是这题程序是运用了C++自带的队列,结合了STL的处理,所以程序写的比较简洁
#include <queue>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

struct bjj{
	int x,step;
}st;
queue <bjj> q;
int vis[200000];
int n,k;
int BFS(){
	while (!q.empty()) q.pop();//多组数据,每次都要清空队列
	memset(vis,0,sizeof vis);//将访问数组初始化
	vis[st.x]=1;//将起始位置标注为访问过
	q.push(st);//将初始位置加入队列
	while (!q.empty()){
		bjj now=q.front();
		if (now.x==k) return now.step;//找到了就直接返回值
		for (int j=0;j<3;j++){//3种情况枚举
			bjj next=now;
			if (j==0) next.x=next.x+1;
			else if (j==1) next.x=next.x-1;
			else if (j==2) next.x=next.x*2;
			next.step++;//步数加1
			if (next.x==k) return next.step;
			if (next.x>=0 && next.x<=200000 && !vis[next.x]){//判断是否越界
				vis[next.x]=1;
				q.push(next);
			}
		}
		q.pop();
	}
	return 0;
}
int main(){
	while (~scanf("%d %d", &n, &k)){  
		st.x=n;
		st.step=0;
		printf("%d\n", BFS());  
	}
	return 0;
}

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值