poj3278--Catch That Cow(BFS+裁剪记录)

来源:互联网 发布:java中多态的理解 编辑:程序博客网 时间:2024/06/08 15:50

Catch That Cow
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 48020 Accepted: 15054

Description

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 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 - 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?

Input

Line 1: Two space-separated integers: N andK

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.
#include <cstdio>#include <cstdlib>#include <string.h>#include <string>#include <math.h>#include <algorithm>#include <iostream>#include <queue>#include <stack>#include <map>#include <set>using namespace std;int i,j,t,n,k,cur;int visted[200010];int bfs(){memset(visted, 0, sizeof(visted));int step=0;queue<int> q,qq,tmp;q.push(n);visted[n]=1;while(!q.empty()){while(!q.empty()){cur = q.front();q.pop();if(cur == k)  return step;if(cur<k){if(visted[2*cur]==0){qq.push(2*cur);visted[2*cur] = 1;}if(visted[cur+1]==0){qq.push(cur+1);visted[cur+1] = 1;}}if(cur>0){if(visted[cur-1]==0){qq.push(cur-1);visted[cur-1] = 1;}}}tmp=qq;qq=q;q=tmp;step++;}}int main(){    cin>>n>>k;    cout<<bfs()<<endl;    return 0;}



原创粉丝点击