HDU 2717:Catch That Cow 【bfs】

来源:互联网 发布:.net 可变sql数据库类 编辑:程序博客网 时间:2024/05/17 03:49

题目链接

Catch That Cow

Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 68   Accepted Submission(s) : 28
Problem 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 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 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

 

注意n>k的情况;

AC-code:

#include<cstdio>#include<cstring>#include<queue>#define INF 0xfffffffint n,k,ans,vis[100050];using namespace std;struct node{int v,step;}temp,a;int jud(struct node p){return p.v<=100000&&p.v>=0&&p.step<ans&&!vis[p.v];}void bfs(int b){a.v=b;a.step=0;vis[b]=1;queue<node>q;q.push(a);while(!q.empty()){a=q.front();q.pop();for(int i=0;i<3;i++){if(i==0){temp.v=a.v+1;temp.step=a.step+1;}else if(i==1){temp.v=a.v-1;temp.step=a.step+1;}else{temp.v=a.v*2;temp.step=a.step+1;}if(jud(temp)){if(temp.v==k){if(ans>temp.step)ans=temp.step;continue;}q.push(temp);vis[temp.v]=1;}}}}int main(){ans=INF;memset(vis,0,sizeof(vis));scanf("%d%d",&n,&k);if(n>=k)printf("%d\n",n-k);else{bfs(n);printf("%d\n",ans);}return 0;}


 

0 0
原创粉丝点击