POJ-3278 Catch that cow

来源:互联网 发布:马氏链模型matlab编程 编辑:程序博客网 时间:2024/06/07 03:39

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 X - 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<iostream> #include<queue> using namespace std; queue<int>sm;//宽搜用队列 int d[200001]={0},start,end;//d[]代表走到当前点需要的最少步数 int search (){ sm.push(start); for(int i=0;i<=200000;i++)d[i]=1001110;//初始化 d[start]=0; while(sm.size()){ int p=sm.front();sm.pop(); if(p==end)break; if((p-1)>=0&&d[p]+1<d[p-1]){//边界条件是0 d[p-1]=d[p]+1; sm.push(p-1); }  if(p<n&&d[p]+1<d[p+1]){//若小于n才能+1 d[p+1]=d[p]+1; sm.push(p+1); }  if(p<100001&&d[p]+1<d[2*p]){//小于n才能乘2 d[p*2]=d[p]+1; sm.push(p*2); }  } return d[end]; } int main(){
cin>>start>>end; cout<<search(); }


原创粉丝点击