(BFS搜索)【HDU 2717】Catch That Cow

本文分享了解决HDU 2717问题的经验,通过使用BFS算法并结合vis数组来记录节点的状态及路径长度,有效地简化了代码结构,实现了对任意起点到终点最短路径的快速求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2717

思路挺简单的,莫名其妙一直敲不对。。全删了重新敲一遍就过了……

看网上一般有两种做法,一种是用struct存位置和步数,感觉复杂了点。直接用vis数组存步数的话,既可以标记是否走过这个状态,也可以记录步数。


/*
* @Author: Samson
* @Date:   2018-04-24 14:33:18
* @Last Modified by:   Samson
* @Last Modified time: 2018-04-24 17:19:05
*/
//   @URL : http://acm.hdu.edu.cn/showproblem.php?pid=2717
#include<iostream>	
#include<queue>
#include<cstring>
#include<algorithm>
#include <cstdlib>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long LL;
const int MAXN = 1e6+10;

int n,k,vis[MAXN],dir[] = {-1,1,0};

void bfs()
{
	memset(vis,0,sizeof vis);
	queue<int> que;
	int cur,next;
	cur = n;
	vis[cur] = 0;
	que.push(cur);
	while(que.size())
	{
		cur = que.front();
		que.pop();
		dir[2] = cur; //第三种,*2的转换成+cur
		for(int i = 0; i < 3; ++i)
		{
			next = cur+dir[i];
			if(next<0 || next>MAXN)
				continue;
			if(!vis[next])
			{
				vis[next] = vis[cur]+1;
				que.push(next);
			}
			if(next == k)
			{
				cout<<vis[next]<<'\n';
				return;
			}
		}
	}
}

int main(void)
{
	while(cin>>n>>k)
	{
		if(n == k)
			cout<<0<<'\n';
		else if(n>k)
			cout<<n-k<<'\n';
		else
			bfs();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值