HDU 2717 Catch That Cow

2014-11-24 11:56:00 · 作者: · 浏览: 0

Catch That Cow

Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6458 Accepted Submission(s): 2052


Problem 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

HintThe 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. 

题意:给定任意的两个坐标n,k,农夫现在在坐标n处,农夫可以选择走到坐标n+1,n-1 或者2*n处,问至少经过多少步可以从n走到k处。

刚开始用的DFS,没看清数据量,超时是必须的。 后改成BFS进行搜索。能搜到的所有坐标只能是0-k+1.

#include 
  
   
#include 
   
     #include 
    
      #include 
     
       #include 
      
        #include 
       
         using namespace std; const int MAX = 100002; int n,k,ans; int dist[MAX]; queue
        
          que; bool yes(int x){ if(x>=0 && x<=k+2 && dist[x]==-1)return true; return false; } int bfs(int x){ que.push(x); dist[x] = 0; while(!que.empty()){ x = que.front(); que.pop(); if(x==k)break; if(yes(x+1)){ dist[x+1] = dist[x] + 1; que.push(x+1); } if(yes(x-1)){ dist[x-1] = dist[x] + 1; que.push(x-1); } if(yes(x*2)){ dist[2*x] = dist[x] + 1; que.push(2*x); } } return dist[k]; } int main(){ //freopen("in.txt","r",stdin); while(scanf("%d %d",&n,&k)!=EOF){ if(n>=k){ printf("%d\n",n-k); continue; } while(!que.empty()){ que.pop(); } ans = INT_MAX; memset(dist,-1,sizeof(dist)); ans = bfs(n); printf("%d\n",ans); } return 0; }