暑期第一弹<搜索> C - Catch That Cow(BFS)
来源:互联网 发布:多线程实例 java 编辑:程序博客网 时间:2024/06/02 06:57
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
Hint
题意:有一个农夫在N位置,他得牛在K位置。他每一步可以向左走一步,向右走一步,走到当前位置的2倍处。问农夫碰到牛所需的最短步骤。
思路:BFS三个状态,初始为N的位置。边界判断!!!可行判断!!!
代码如下:
#include <iostream>#include <queue>#include <cstring>using namespace std;struct Node{ int id; int cont;};int n,k;int visit[200005]; //虽然没看到题意说每个位置只能走一次,但是不标记的话会内存超限void bfs(){ queue <Node> Q; while(!Q.empty()) Q.pop(); Node h; h.id = n; h.cont = 0; visit[n] = 1; Q.push(h); while(!Q.empty()){ Node res = Q.front(); Q.pop(); if(res.id == k){ cout<<res.cont<<endl; break; } int ID = res.id; int Cont = res.cont; if(ID <= k && !visit[ID+1]){ //可行判断 visit[ID+1] = 1; Node temp; temp.id = ID+1; temp.cont = Cont+1; Q.push(temp); } if(ID >= 1 && !visit[ID-1]){ //可行判断 visit[ID-1] = 1; Node temp; temp.id = ID-1; temp.cont = Cont+1; Q.push(temp); } if(ID <= k && !visit[ID*2]){ //可行判断 visit[ID*2] = 1; Node temp; temp.id = ID*2; temp.cont = Cont+1; Q.push(temp); } }}int main(){ while(cin>>n>>k){ memset(visit,0,sizeof(visit)); bfs(); } return 0;}
- 暑期第一弹<搜索> C - Catch That Cow(BFS)
- poj3278 Catch That Cow(bfs搜索)
- Catch That Cow(BFS)
- Catch That Cow(BFS)
- Catch That Cow (BFS)
- Catch That Cow (BFS)
- Catch That Cow(BFS)
- POJ 3278 Catch That Cow BFS(第一题)
- HDU 2717 Catch That Cow (搜索 - BFS)
- poj 3278 Catch That Cow (bfs搜索)
- POJ3278(BFS广度优先搜索)之Catch That Cow
- Catch That Cow(bfs)
- Catch That Cow+BFS
- Catch That Cow BFS
- Catch That Cow BFS
- Catch That Cow(BFS)
- Catch That Cow BFS
- Catch That Cow (BFS)
- UIKIT详解之UILabel全面解析
- Win10+Caffe+CUDA7.5编译
- window.location.href和window.location.hash的区别
- 如何禁止(表单)用户名、密码自动填充
- C语言的标准
- 暑期第一弹<搜索> C - Catch That Cow(BFS)
- android dp深度解析
- 康托展开与康托逆展开,细节决定成败!
- Mysql 创建字段为varchar类型,但是保存中文数据时报1366错误
- 人力资源管理能否靠数字说话
- Activity中弹软键盘
- sublime text使用技巧
- Qt使用非阻塞事件循环的延时方式
- codeforces Helvetic Coding Contest 2016 D2 The Wall (medium)