Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 111204 | Accepted: 34771 |
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要抓奶牛。
开始输入N(FJ的位置)K(奶牛的位置)。
FJ有三种移动方法:1、向前走一步,耗时一分钟。
2、向后走一步,耗时一分钟。
3、向前移动到当前位置的两倍N*2,耗时一分钟。
问FJ抓到奶牛的最少时间。PS:奶牛是不会动的。
思路:1、如果FJ不在奶牛后面,那么他只有一步步往后移动到奶牛位置了,即N>=K时,输出N-K即可。
2、否则bfs+队列查找(具体见下面的分析&&代码区)
相关算法:
1、STL中的队列。(PS:周四才在数据结构上了解bfs的真正思想,惭愧啊!)
需要的头文件:STL是C++中的 #include<iostream>
using namespace std;
queue队列容器的头文件 #include<queue>
queue队列的相关用法:先进先出(FIFO)
入队push() //即插入元素
出队pop() //即删除元素
front() //读取队首元素
back() //读取队尾元素
empty() //判断队列是否为空
size() //读取队列当前元素的个数
2、bfs思想:节点进行广度优先搜索的顺序。
搜索实现方法(非递归):
算法思想:1.设置一个队列Q,从顶点出发,遍历该顶点后让其进队;
2.出队一个顶点元素,求该顶点的所有邻接点(对应于此题即FJ的三种走法),
对于没有遍历过的邻接点遍历之,并 让其进队;
3.若队空停止,队不空时继续第2步。
关于bfs数据结构思想的详细介绍:http://zh.wikipedia.org/wiki/BFS
#include<iostream> #include<queue> #include<cstring> using namespace std; bool vis[100005];//标记是否访问过 int n,k; struct node { int pos,step; }cur,next; bool ok(int x)//排除访问过和出界情况 { if(x>0&&x<=100000&&!vis[x]) return true; else return false; } int bfs(int x) { memset(vis,0,sizeof(vis)); queue<node> q; cur.pos=x; cur.step=0; vis[cur.pos]=1; q.push(cur); while(!q.empty()) { cur=q.front(); q.pop(); if(cur.pos==k) return cur.step; next.pos=cur.pos-1; if(ok(next.pos)) { next.step=cur.step+1;//步数加1 q.push(next);//入队列 vis[next.pos]=1;//标记已访问 } next.pos=cur.pos+1; if(ok(next.pos)) { next.step=cur.step+1; q.push(next); vis[next.pos]=1; } next.pos=cur.pos*2; if(ok(next.pos)) { next.step=cur.step+1; q.push(next); vis[next.pos]=1; } } } int main() { while(cin>>n>>k) { if(k<=n) cout<<n-k<<endl; else cout<<bfs(n)<<endl; } return 0; }