POJ 3278 Catch That Cow-模拟

来源:互联网 发布:拦沙坝计算软件 编辑:程序博客网 时间:2024/06/06 12:20

Catch That Cow
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 101298 Accepted: 31669

Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN (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 orX+ 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 andK

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

[Submit]   [Go Back]   [Status]   [Discuss]


转载一个逗比题意:

数学老师用你刚刚编写的程序验证了WNJXYK给出的回答,发现他全都是在口胡。老师很生气,后果很严重。于是,WNJXYK决定先跑为妙,他一下子跑出了很远觉得自己很安全就停下来休息了。

我们把世界抽象为一个数轴,老师一开始在点N(0 ≤ N ≤ 100,000),WNJXYK会一直在点K(0 ≤ K ≤ 100,000) 休息,老师每秒钟有两种操作:
1.走路:当前在X,下一秒可以在X+1或X-1
2.闪现:当前在X,下一秒在2*X

现在数学老师想知道,最早在什么时候才能抓住WNJXYK(到达他所在的位置)

分析:BFS模拟一下即可,注意一下不要数组越界;


AC Code:

#include <iostream>#include <algorithm>#include <cstdio>#include <cstring>#include <cmath>#include <cstdlib>#include <vector>#include <queue>#include <stack>#include <string>#include <map>using namespace std;#define LL long long#define INF 0x3f3f3f3f#define eps 1const int maxn=200000+50;struct node{    int n,time;};int vis[maxn];node walk(node a,int i){    if(i==1) a.n++;    else if(i==2) a.n*=2;    else a.n--;    a.time++;    return a;}void bfs(int n,int k){    if(k<=n){        printf("%d\n",n-k);        return;    }    memset(vis,0,sizeof vis);    vis[n]=1;    queue<node> q;    node s; s.n=n; s.time=0;    q.push(s);    while(!q.empty()){        s=q.front(); q.pop();        if(s.n==k){            printf("%d\n",s.time);            return;        }        for(int i=1;i<=3;i++){            node t=walk(s,i);            if(t.n>maxn||t.n<0) continue;            if(!vis[t.n]){                q.push(t);                vis[t.n]=1;            }        }    }}int main() {    int n,k;    while(~scanf("%d%d",&n,&k)){        bfs(n,k);    }    return 0; }




原创粉丝点击