码迷,mamicode.com
首页 > 其他好文 > 详细

POJ3278Catch That Cow(线性模型)(BFS)

时间:2015-01-21 22:38:55      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:

Catch That Cow
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 49988   Accepted: 15679

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.

传送门

题意:实在鬼畜...John在0~100,000的某个位置上,牛也在某个位置上问,John通过题述的+1,-1,*2这几种变换方式能最少变换几次捉到牛。

求最少变换,用bfs,注意标记到达的数就不能再到达,否则会结束不了循环,而且有几个剪枝:

1.John不需要跑到负数的地方,因为跑到负数显然是由-1造成的,下一步只能+1,就等于走了两步废棋。

2.John不需要跑到100,000以外的地方,因为跑到100,000以外肯定是打算*2后再减去几次到达牛的位置。但是牛在100,000以内,*2后到达的位置一定是偶数,

所以离100,000最近的偶数是100002,所以还要减2步,所以一共走了3步,所以John从50,001的位置不需*2,直接-1,再*2也到达了100,000位置,所以又多走了一步废棋,若*2后不是100002,离100,000更远那么就多走了更多废棋。

//916K	141MS
#include<cstdio>
#include<queue>
#include<iostream>
using namespace std;
queue<pair<int,int> >que;//记录到达的位置和移动的步数
int n,m;
bool book[100100]; 
void bfs()
{
    que.push(make_pair(n,0));
    book[n]=1;
    while(!que.empty())
    {
        pair<int,int> t=que.front();
        que.pop();
        if(t.first==m) {printf("%d\n",t.second); break;}
        if(t.first+1<=100000&&!book[t.first+1]) {que.push(make_pair(t.first+1,t.second+1));book[t.first+1]=1;}
        if(t.first-1>=0&&!book[t.first-1])   {que.push(make_pair(t.first-1,t.second+1));book[t.first-1]=1;}
        if(t.first*2<=100000&&!book[t.first*2]) {que.push(make_pair(t.first*2,t.second+1));book[t.first*2]=1;}
    }
}
int main()
{
    scanf("%d%d",&n,&m);
    bfs();
    return 0;
}




POJ3278Catch That Cow(线性模型)(BFS)

标签:

原文地址:http://blog.csdn.net/kalilili/article/details/42975125

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!