hdu 2717 Catch That Cow(BFS)

本文介绍了一道经典的最短路径问题——从N到K的最少步数问题,并通过广度优先搜索(BFS)算法解决。提供了完整的C++实现代码,包括初始化标志数组、使用队列进行节点遍历等关键步骤。

原题链接:

http://acm.hdu.edu.cn/showproblem.php?pid=2717



题目大意:

从N到K最少需要几步

两种移动方式:

1. pos+1或者pos-1

2. pos*2


简单的BFS。

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<utility>
using namespace std;
const int MAXN=100000+1;

typedef pair<int,int> ii;//first位置second第几步

bool flog[MAXN];

int BFS(int N,int K)
{
	memset(flog,0,sizeof(flog));
	queue<ii>q;
	ii pos;
	pos.first=N;
	pos.second=0;
	q.push(pos);
	flog[N]=true;
	while(!q.empty())
	{
		pos=q.front();
		q.pop();
		if(pos.first==K) return pos.second;
		ii temp;
		if(pos.first+1<=K&&!flog[pos.first+1])//三种下一步的位置
		{
			temp.first=pos.first+1;
			temp.second=pos.second+1;
			flog[temp.first]=true;
			q.push(temp);
		}
		if(pos.first-1>=0&&!flog[pos.first-1])
		{
			temp.first=pos.first-1;
			temp.second=pos.second+1;
			flog[temp.first]=true;
			q.push(temp);
		}
		if(pos.first+pos.first<MAXN&&!flog[pos.first+pos.first])
		{
			temp.first=pos.first+pos.first;
			temp.second=pos.second+1;
			flog[temp.first]=true;
			q.push(temp);
		}
	}

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





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值