首页 > 代码库 > Poj 3278 Catch That Cow

Poj 3278 Catch That Cow

1.Link:

http://poj.org/problem?id=3278

2.Content:

Catch That Cow
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 48245 Accepted: 15114

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 - 1 or + 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

3.Method:

4.Code:

 1 #include<iostream> 2 #include<queue> 3  4 using namespace std; 5  6 //(0 ≤ N ≤ 100,000) 7 #define MAX 200002 8 int a[MAX]; 9 int main()10 {11     int i,j;12     int x,y;13     int m,n;14     cin>>x>>y;15     queue<int> q;16     a[x]=1;17     q.push(x);18     while(!q.empty())19     {20         m=q.front();21         if(m==y) {cout<<a[m]-1;break;}22         else23         {24             n=m-1;25             if(n>=0&&n<MAX&&a[n]==0)26             {27                 a[n]=a[m]+1;28                 q.push(n);29             }30             n=m+1;31             if(n>=0&&n<MAX&&a[n]==0)32             {33                a[n]=a[m]+1;34                q.push(n);35             }36             n=m*2;37             if(n>=0&&n<MAX&&a[n]==0)38             {39                a[n]=a[m]+1;40                q.push(n);41             }42         }43         q.pop();44     }45     //system("pause");46     return 0;47 }

 

5.Reference:

Poj 3278 Catch That Cow