POJ-3278 Catch That Cow
来源:互联网 发布:桔城seo伪原创工具 编辑:程序博客网 时间:2024/06/03 08:40
#include <iostream>#include <cstring>#include <cstdio>#include <queue>using namespace std;const int maxn = 2e5;int sign[maxn];int n, k;struct Step{ int l; int step;} start;queue<Step> location;int bfs(){ if(start.l == k) return start.step; while(!location.empty()) location.pop(); location.push(start); sign[start.l] = 1; while(!location.empty()) { Step now = location.front(); location.pop(); for(int i = 0; i < 3; i ++) { Step next = now; if(i == 0) next.l += 1; else if(i == 1) next.l -= 1; else if(i == 2) next.l *= 2; next.step ++; if(next.l == k) return next.step; if(next.l >= 0 && next.l <= maxn && sign[next.l] == 0) { location.push(next); sign[next.l] = 1; } } }}int main(void){ while(~scanf("%d %d", & n, & k)) { start.l = n; start.step = 0; memset(sign, 0 , sizeof(0)); printf("%d\n",bfs()); }}
题意:知道农民的位置n 知道牛的位置k 农民有三种移动方式。一种是-1(后退一步) 一种+1(前进一步) 另一种×2(瞬移)。问最快抓住牛的步数。
题解:(摘自yangjiaronga的专栏)
在搜索专题中,我们经常用到两种算法,一种是DFS(深度优先搜索)和BFS(广度优先搜索)。在搜索中 ,我们采用队列的形式,就是先进先出,就好比我们排队吃饭一样,我排在前面的,我就可以先打到饭。在搜索中,我们讲符合条件的点放进队列用,在取出来用的时候,就是先把放进去的先取出来使用。本题我采用的是BFS算法。因为BFS算法比较通用。在本题中,农场主有三种方式,一种是往前走一步,一种是往后走一步,还有一种是瞬移到原来位置的两倍。在BFS循环的时候就可以将这三种操作进行处理。 走过的位置标记。代表不会走回原来的位置。因为不标记的话,会导致死循环,爆内存。在找到牛的时候跳出。在判断是否越界的时候,不能像题目中所说,当牧场主所在的位置大于10W的时候,就认为他越界。因为他有可能先去到100010的时候 ,在回来。所以再判断是时候,越界的最大值最好为20W。这样就不会出错了。
0 0
- poj 3278 Catch That Cow
- POJ 3278 Catch That Cow
- poj 3278 catch that cow
- poj 3278 Catch That Cow
- POJ 3278 Catch That Cow
- Poj 3278 Catch That Cow
- POJ 3278 Catch That Cow
- POJ 3278 Catch That Cow
- POJ 3278 Catch That Cow
- poj 3278 Catch That Cow
- POJ 3278 Catch That Cow
- poj 3278 Catch That Cow
- poj 3278 Catch That Cow
- POJ 3278 Catch That Cow
- POJ 3278 - Catch That Cow
- POJ 3278 Catch That Cow
- POJ 3278 Catch That Cow
- POJ-3278-Catch That Cow
- 如何在内核中添加新的驱动配置选项
- UI学习概览
- 太陰逆生倒成 太陽倒生逆成
- hdu 1874 畅通工程续 (裸的 Dijkstra)
- 使用ffmpeg.exe进行转码参数说明
- POJ-3278 Catch That Cow
- [LeetCode] Binary Tree Zigzag Level Order Traversal
- OpenSSL “心脏滴血”漏洞
- uva 动态规划 437 The Tower of Babylon
- vi编译器插件
- Python安装
- C++数组
- uva 705
- Struts2零配置