POJ3278 抓奶牛 BFS
来源:互联网 发布:能查高数题的软件 编辑:程序博客网 时间:2024/04/28 12:51
嗯弱弱的开始了BFS的旅程,不知从哪里找到了那个做题顺序。于是就按着那个来了。
题目描述:
嗯这个题目是给你两个数,一个是农夫的坐标n,一个是奶牛的坐标k,坐标轴大小在0到100000之间,然后农夫有三种行进的方法,分别是n+1 , n-1 , 2*n,然后我们就要求的是农夫追上奶牛所用的最短的步数嗯。
算法思想:
来,都告诉你是BFS了,那就来实现吧。
大意就是先把农夫位置n推进队列,然后因为队列是先进先出嘛,所以就在每一层都把三种操作做一遍看能不能达到最终的状态。如果不能的话再开到下一层。因为是最简单的BFS所以在这里也不多赘述了。
代码部分:
#include <iostream>#include <queue>#include <string.h>using namespace std;bool vis[101117];int n, k;int main() {queue <int> q;cin >> n >> k;memset(vis, 0, sizeof(vis));bool flag = false;int steps = 0;vis[n] = 1;q.push(n);if (n != k) {while (!q.empty() && !flag) {int pos;int size = q.size();steps++;while (size--) {pos = q.front();q.pop();if (pos + 1 == k || pos - 1 == k || pos * 2 == k) {flag = 1; break;}if (pos + 1 >= 0 && pos + 1 <= 100000 && !vis[pos + 1]) {vis[pos + 1] = 1;q.push(pos + 1);}if (pos - 1 >= 0 && pos - 1 <= 100000 && !vis[pos - 1]) {vis[pos - 1] = 1;q.push(pos - 1);}if (pos >= 0 && 2 * pos <= 100000 && !vis[pos * 2]) {vis[pos * 2] = 1;q.push(pos * 2);}}}}cout << steps << endl;return 0;
0 0
- POJ3278 抓奶牛 BFS
- poj3278 抓牛(bfs)
- [BFS]最简题-抓奶牛
- poj3278 BFS
- POJ3278---bfs
- poj3278 bfs
- poj3278(bfs)
- POJ3278 -- BFS
- POJ3278--BFS
- poj3278-bfs
- POJ3278 BFS
- poj3278 bfs
- POJ3278 BFS
- 广度优先搜索bfs与抓住那头奶牛(Catch that cow, poj3278)
- 照葫芦画瓢的BFS,poj3278
- POJ3278 BFS 水题
- 0.8poj3278(bfs)
- poj3278~bfs基础题
- JSONObject对象的optXXX和getXXX的区别
- Linux块设备加密之dm-crypt分析
- java异常机制详解
- uva 10604(dp + 回溯)
- DICOM医学图像处理:DICOM存储操作之 “多幅JPG图像数据存入DCM文件”
- POJ3278 抓奶牛 BFS
- 深入浅出Android Gradle构建系统(二:项目结构)
- 基本的递归问题--河内之塔
- uva10604(DP +回溯)
- 4、 xcode在Archive生成安装包时遇到ld: library not found for -lPods
- 微软苏州校招笔试 12月27日
- 几条命令-可能有些古董
- 计算机原理学习 -- x86-32 CPU和内存管理之分段管理
- windows操作系统对于程序运行时堆栈的管理的研究