C++广度优先搜索算法之抓住那头牛(Catch that cow)
来源:互联网 发布:复旦大学大数据研究院 编辑:程序博客网 时间:2024/06/04 19:38
抓住那头牛:
农夫知道一头牛的位置,想要抓住它。农夫和牛都位于数轴上,农夫起始位于点N(0<=N<=100000),牛位于点K(0<=K<=100000)。农夫有两种移动方式:
1、从X移动到X-1或X+1,每次移动花费一分钟
2、从X移动到2*X,每次移动花费一分钟
假设牛没有意识到农夫的行动,站在原地不动。农夫最少要花多少时间才能抓住牛?
Catch that cow:
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN (0 ≤N ≤ 100,000) on a number line and the cow is at a pointK (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 pointX to the pointsX- 1 orX+ 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?
以上是题目,具体输入输出如下:
输入
两个整数,N和K。
输出
一个整数,农夫抓到牛所要花费的最小分钟数。
代码如下:
#include<cstdio>const int sb=1e6;bool mark[sb+1];int que[sb+1],pre[sb+1],n,k;int next;void print(int x){int num=0;while(pre[x]){num++;x=pre[x];}printf("%d",num);}void bfs(){if(n==k){printf("0");return ;}int head=0,tail=1;que[1]=n;mark[n]=true;while(head!=tail){head++;for(int i=0;i<3;i++){switch(i){case 0: next=que[head]+1;break;case 1: next=que[head]-1;break;case 2: next=que[head]*2;break;}if(next>=0&&next<=sb&&mark[next]!=true){tail++;que[tail]=next;mark[next]=true;pre[tail]=head;if(next==k) {print(tail);head=tail;break;}}}}}int main(){scanf("%d%d",&n,&k);bfs();}
- C++广度优先搜索算法之抓住那头牛(Catch that cow)
- 广度优先搜索bfs与抓住那头奶牛(Catch that cow, poj3278)
- POJ 3278:Catch That Cow 抓住那头牛
- (广度优先搜索)算法题-poj3278 Catch That Cow
- POJ3278(BFS广度优先搜索)之Catch That Cow
- poj3287 Catch That Cow(广度优先搜索)
- Catch That Cow-----广度优先搜索
- POJ3278 - Catch That Cow - 广度优先搜索
- Catch That Cow(广度优先搜索_bfs)
- Catch That Cow-广度优先搜索-POJ3278
- Catch That Cow广度优先搜索
- 广度优先搜索 入门:抓住那头牛
- 广度优先搜索--抓住那头牛(poj 3278)
- poj 4001 抓住那头牛 (广度优先搜索算法)
- 广度优先搜索-抓住那头牛(算法基础 第8周)
- 广度优先搜索之入门题目->抓住那只牛
- OpenJudge 2.5-2971 Catch That Cow(抓住那头牛)
- POJ 3278 Catch That Cow(BFS广度优先搜索)
- Python3 如何优雅地使用正则表达式(详解三)
- Docker 镜像小结
- HiveSQL常见问题总结
- (136)聚光源
- Kdd9数据集
- C++广度优先搜索算法之抓住那头牛(Catch that cow)
- WKWebView详解&WKWebVieW和JS交互
- Java线程池
- 哥德巴赫猜想(难度:1颗星)
- MySQL之事务&隔离级别&死锁
- 查询linux某端口在外面能否正常访问
- linux下查看局域网的所有主机的ip地址
- Hive On Spark报错:Exception in thread "main" java.lang.NoClassDefFoundError: scala/collection/Iterable
- Staple- Complementary Learners for Real-Time Tracking 阅读汇总