POJ-3278&&HDU-2717--Catch That Cow---BFS广搜
来源:互联网 发布:什么是数据存储 编辑:程序博客网 时间:2024/05/18 18:21
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
Line 1: Two space-separated integers: N and K
Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input
5 17
Sample Output
4
Hint
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
题意:给两个点 a,b。一开始牛在a,每次走的步数都可以为a-1 a+1 a*2.问走到点b最少需要几步。
解题思路:如果a>=b,那么直接输出a-b。否则,将每一个可能要走的步数入队,记录步数用了一个num数组。简述一下num数组的作用:
现在奶牛在点为5的位置上,让num[5]=0。现在与5相关的点有10,4,6。这是要走的第一步,于是num[10]=num[5]+1,num[4]=num[5]+1,num[6]=num[5]+1。以此类推,直到找到点b,num[b]的值就是牛走的最短的步数。
#include<iostream>#include<queue>#include<cstring>using namespace std;int n,k;const int M=1e5;int flag[2*M+50];//数组要开到2*M,因为如果牛已经走到第10W步的时候,20W也要入队。int num[2*M+50];queue<int>q;void bfs(){ q.push(n); flag[n]=1; while(!q.empty()) { int t=q.front(); q.pop(); int t1=t+1,t2=t-1,t3=t*2; if(t1==k||t2==k||t3==k) { num[k]=num[t]+1; break; } if(t1<=2*M&&!flag[t1]) { q.push(t1); flag[t1]=1; num[t1]=num[t]+1; } if(t2>=0&&!flag[t2]) { q.push(t2); flag[t2]=1; num[t2]=num[t]+1; } if(t3<=2*M&&!flag[t3]) { q.push(t3); flag[t3]=1; num[t3]=num[t]+1; } }}int main(){ while(cin>>n>>k) { memset(flag,0,sizeof(flag)); memset(num,0,sizeof(num)); while(!q.empty()) q.pop(); if(n>=k) cout<<n-k<<endl; else { bfs(); cout<<num[k]<<endl; } }}
- POJ-3278&&HDU-2717--Catch That Cow---BFS广搜
- POJ 3278 / hdu 2717 Catch That Cow (广搜)
- poj 3278 Catch that cow(BFS 广搜)
- poj 3278 Catch That Cow(bfs广搜)
- POJ-3278-Catch That Cow-广搜(BFS)
- POJ 3278 Catch That Cow(广搜BFS)
- hdu 2717 Catch That Cow(广搜bfs)
- poj 3278 Catch That Cow 广搜
- -----广搜 POJ 3278-Catch That Cow
- poj 3287 -- Catch That Cow (bfs 广搜)
- POJ 3278 && HDU 2717 Catch That Cow(bfs)
- POJ-3278 && HDU-2717 Catch That Cow 线性BFS题目
- POJ3278 Catch That Cow(广搜BFS)
- poj3278-catch that cow(bfs广搜)
- POJ3278 Catch That Cow(广搜BFS)
- POJ 3728 Catch That Cow (广搜)
- poj 3278 Catch That Cow(简单的广搜+剪枝)
- POJ-3278 Catch That Cow(广搜+剪枝)
- JQuery的父、子、兄弟节点查找,节点的子节点循环
- 界面层bug笔记
- JAVA SE面试题 01
- Android——onKeyDown与onBackPressed(未完)
- 机器视觉相机镜头选型与应用
- POJ-3278&&HDU-2717--Catch That Cow---BFS广搜
- 字典树详解
- C# windowsForm CS 窗体基础知识记录
- HDOJ 2062 Subset sequence (dp)
- 截取 substring(),substr(),slice(),splice(),split()
- 大数据分析建模思路技巧和算法的特征
- TSQL学习笔记
- [随心译]2017.8.4-研究表明男人首次看色情内容时的年龄会影响他们对女性的态度
- 《道德经》第五十四章