POJ 3278 Catch That Cow(BFS)
来源:互联网 发布:上海网络借贷平台备案 编辑:程序博客网 时间:2024/05/22 12:37
Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.
* Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.
If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?
Input
Output
Sample Input
5 17
Sample Output
4题目大意:FJ的牛逃跑了,他想立即抓住它。FJ和牛都在一个数轴上,FJ在位置N,牛在位置K。FJ每分钟可以移动到N - 1、N + 1 或 2 * N 处,而牛却不会动。给出FJ和牛的位置,求FJ抓住牛所需要的最短时间。
解题思路:将每次FJ可能的移动情况入队,BFS即可。注意剪枝,先判断是否超出范围再判断是否访问过,如果顺序反过来的话,数组要开200000+,否则会RE。
代码如下:
#include <cstdio>#include <cstring>#include <algorithm>#include <queue>using namespace std;const int maxn = 100005;int posn,posk;int t[maxn];int bfs(){ memset(t,-1,sizeof(t)); queue<int> que; que.push(posn); t[posn] = 0; int temp; while(que.size()){ temp = que.front(); que.pop(); if(temp == posk){ break; } int next; next = temp - 1; if(0 <= next && next <= maxn - 5 && t[next] == -1){ que.push(next); t[next] = t[temp] + 1; } next = temp + 1; if(0 <= next && next <= maxn - 5 && t[next] == -1){ que.push(next); t[next] = t[temp] + 1; } next = temp + temp; if(0 <= next && next <= maxn - 5 && t[next] == -1){ que.push(next); t[next] = t[temp] + 1; } } return t[temp];}int main(){ while(scanf("%d %d",&posn,&posk) != EOF){ printf("%d\n",bfs()); } return 0;}
- poj 3278 Catch That Cow(bfs)
- POJ 3278 Catch That Cow (BFS)
- POJ 3278 Catch That Cow(BFS)
- POJ--3278:Catch That Cow (BFS)
- POJ 3278 - Catch That Cow(BFS)
- POJ 3278 Catch That Cow (BFS)
- POJ - 3278 - Catch That Cow (BFS)
- POJ 3278 Catch That Cow (BFS)
- POJ 3278 Catch That Cow (BFS)
- POJ 3278-Catch That Cow(bfs)
- POJ-3278-Catch That Cow(BFS)
- POJ 3278Catch That Cow(BFS)
- POJ 3278 Catch That Cow(BFS)
- poj 3278 Catch That Cow(BFS)
- poj 3278 Catch That Cow (BFS)
- POJ 3278 Catch That Cow (BFS)
- POJ.3278 Catch That Cow (BFS)
- POJ 3278Catch That Cow (bfs)
- Catch That Cow
- 纠正对Fragment Transaction BackStack的误解
- HDU5726
- C++之STL(7) queue队列
- linux部署web项目到tomcat下(图文详解)
- POJ 3278 Catch That Cow(BFS)
- 10个值得深思的PHP面试问题
- 【Codeforces】-698A-Vacations(贪心)
- JSONP
- JavaScrip使用语法规范
- codeforces 350 div2 D Magic Powder - 2 二分
- conv是卷积运算,同时也可以做多项式的乘法
- ubuntu下Android4.4 CTS搭建(一)
- 高并发数据结构Disruptor解析(3)