POJ 3278 Catch That Cow 搜索

来源:互联网 发布:linux u盘挂载位置 编辑:程序博客网 时间:2024/05/17 08:09
http://poj.org/problem?id=3278


Catch That Cow
Time Limit: 2000MS        Memory Limit: 65536K
Total Submissions: 44629        Accepted: 13954

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



#include<iostream>#include<cstring>#include<queue>using namespace std;int n,m,ans;int v[200002];struct node {int time,x;};void bfs(int T){node now,temp;queue<node>  q;now.time=0;now.x=T;memset(v,0,sizeof(v));v[now.x]=1;q.push(now);while(!q.empty()){now=q.front();q.pop();if(m==now.x) {if(now.time<ans)   ans=now.time;}elsefor(int i=0;i<3;i++){if(i==0)  temp.x=now.x+1;if(i==1)  temp.x=now.x-1;if(i==2)  temp.x=2*now.x;if(temp.x>=0&&temp.x<=100000&&!v[temp.x]){temp.time=now.time+1;v[temp.x]=1;q.push(temp);}}}}int main(){while(cin>>n>>m){ans=10000;if(n>=m)cout<<n-m<<endl;else{bfs(n);cout<<ans<<endl;}}return 0;}

0 0
原创粉丝点击