| Time Limit: 2000MS | Memory Limit: 65536K | |
| Total Submissions: 35117 | Accepted: 10823 |
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
Output
Sample Input
5 17
Sample Output
4
Hint
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
int n,k,map[100005]={0};
struct node
{
int t;
int x;
};
queue<node> q;
int find(node start)
{
int i;
q.push(start);
map[start.x]=1;
while(!q.empty())
{
node temp;
temp=q.front();
q.pop();
for (i=1; i<=3; i++)
{
node next;
if (i==1)
{
next.x=temp.x-1;
if (next.x>=0 && next.x<100001 && !map[next.x])
{
next.t=temp.t+1;
q.push(next);
map[next.x]=1;
}
}
if (i==2)
{
next.x=temp.x+1;
if (next.x>=0 && next.x<100001 && !map[next.x])
{
next.t=temp.t+1;
q.push(next);
map[next.x]=1;
}
}
if (i==3)
{
next.x=temp.x*2;
if (next.x>=0 && next.x<100001 && !map[next.x])
{
next.t=temp.t+1;
q.push(next);
map[next.x]=1;
}
}
if (next.x==k)
return next.t;
}
}
}
int main ()
{
node start;
start.t=0;
int s=0;
cin>>start.x>>k;
if (start.x==k)
cout<<s<<endl;
else
{
s=find(start);
cout<<s<<endl;
}
return 0;
}

本文详细解读了CATCH THAT COW问题的解决方案,包括问题背景、输入输出规范、核心算法思想及代码实现。通过广度优先搜索算法寻找最优路径,解决Farmer John追赶逃逸奶牛的问题。
308

被折叠的 条评论
为什么被折叠?



