[POJ](3278)Catch That Cow ---BFS(图)
Catch That Cow
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 96514 | Accepted: 30289 |
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
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.
题意:John要去抓他的奶牛,现在John在n位置,奶牛在k位置。奶牛位置不变,
John有三种方式去其他位置 :
①:向后走一步,耗时一分钟。
②:向前走一步,耗时一分钟。
③:到达John所处位置的两倍位置,耗时一分钟。
问:John如何用时最少找到他的奶牛?
思路:将问题抽象为图,John在某一位置N,有三种位置可走,N-1,N+1,2*N,即任一位置都有与该位置连通的三个邻接点。采用BFS的算法,不断搜索位置,先到位置k的路径即为耗时最少的。
AC代码:
注:代码在POJ上用C++交AC,G++交WA。可能是编译器优化的原因( ⊙ o ⊙ )
#include<iostream> #include<queue> #include<cstring> using namespace std; const int maxn=100005; bool vis[maxn]; int sum[maxn]; int bfs(int n,int k) { queue<int>q; vis[n]=true; sum[n]=0; q.push(n); int next; while(!q.empty()) { int now=q.front(); q.pop(); for(int i=1;i<=3;i++) //每个点有三种走法 { if(i==1) next=now-1; //向后走一步 else if(i==2) next=now+1; //向前走一步 else if(i==3) next=2*now; //向前走到当前位置的两倍位置 if(next<0 || next>maxn) //防止越界 continue; if(!vis[next]) { vis[next]=true; sum[next]=sum[now]+1; q.push(next); } if(next==k) //先到达奶牛位置的肯定是用时最短的 return sum[next]; } } } int main() { int n,k; while(cin>>n>>k) { memset(vis,false,sizeof(vis)); memset(sum,0,sizeof(sum)); if(n>=k) cout<<n-k<<endl; else cout<<bfs(n,k)<<endl; } return 0; }