Catch That Cow
Time Limit : 5000/2000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 68 Accepted Submission(s) : 18
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
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?
* 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.
Source
USACO 2007 Open Silver
这题必须用广搜
广搜出来的是最小次
要注意 进队列 的数必须 没有扩充过 且 在0--100000内
#include<iostream> #include<queue> #include<algorithm> using namespace std; struct num { int shu;//数目 int chi;//扩充到第几次 }; int main() { int star,end; while(scanf("%d %d",&star,&end)!=EOF) { num a1; a1.shu=star;//开始扩充的数 a1.chi=0; bool used[100005]; int number;//记录次数 memset(used,0,sizeof(used)); queue<num> q; q.push(a1); while(!q.empty()) { num a2; a2=q.front(); q.pop(); if(a2.shu==end)//是目的数 退出 { number=a2.chi; break; } if(used[a2.shu]==0)//没有被扩充过 进行扩充 { used[a2.shu]=1;//标记 num a3; a3.chi=a2.chi+1; a3.shu=a2.shu+1; //+1 if(a3.shu>=0&&a3.shu<=100000&&used[a3.shu]==0)//没有被标记过且在范围内 { q.push(a3); } a3.chi=a2.chi+1; a3.shu=a2.shu-1; //-1 if(a3.shu>=0&&a3.shu<=100000&&used[a3.shu]==0)//没有被标记过且在范围内 { q.push(a3); } a3.chi=a2.chi+1; a3.shu=a2.shu*2; //*2 if(a3.shu>=0&&a3.shu<=100000&&used[a3.shu]==0)//没有被标记过且在范围内 {q.push(a3);} } } printf("%d ",number); } }