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

POJ 3278 Catch That Cow

时间:2014-05-21 14:33:08      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   class   c   code   

Catch That Cow
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 43674   Accepted: 13612

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



题目大意:

告诉你起点位置和终点位置,你可以有三种操作,从某个位置x,可以到达x-1,x+1,2*x,问你从起点到终点最短时间?

解题思路:

利用bfs枚举位置即可

但是刨除以下情况,也就是剪枝一下

1、当x<=0 时,x-1不能到达,这个状态剪掉

2、当x>终点位置时,x+1和2*x均不能到达

解题代码:

#include <iostream>
#include <queue>
using namespace std;

const int maxn=210000;
int marked,visited[maxn];

struct node{
    int pos,t;
    node(int pos0=0,int t0=0){
        pos=pos0;t=t0;
    }
};

int main(){
    int from,to;
    while(cin>>from>>to){
        marked++;
        queue <node> q;
        q.push(node(from,0));
        visited[from]=marked;
        while(!q.empty()){
            node s=q.front();
            q.pop();
            if(s.pos==to){
                cout<<s.t<<endl;
                break;
            }
            if( s.pos-1>=0 && visited[s.pos-1]!=marked){
                visited[s.pos-1]=marked;
                q.push(node(s.pos-1,s.t+1));
            }
            if( s.pos<=to && visited[s.pos+1]!=marked){
                visited[s.pos+1]=marked;
                q.push(node(s.pos+1,s.t+1));
            }
            if( s.pos<=to && visited[s.pos*2]!=marked){
                visited[s.pos*2]=marked;
                q.push(node(s.pos*2,s.t+1));
            }
        }
    }
    return 0;
}





POJ 3278 Catch That Cow,布布扣,bubuko.com

POJ 3278 Catch That Cow

标签:des   style   blog   class   c   code   

原文地址:http://blog.csdn.net/a1061747415/article/details/26343741

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