poj3278Catch That Cow(bfs)

题目

Catch That Cow
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?

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


思路:

广搜思路,以此类推


代码

#include<iostream>
#include<fstream>
#include<string>
#include<algorithm>
#include<math.h>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<vector>
#include<stdio.h>
#include<stdlib.h>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>

using namespace std;

typedef long long LL;
typedef long double real;
typedef vector<int> VI;


/**************************************************************
    Problem: poj3278Catch That Cow
    Ordering: bfs
    Thought: 针对三个可行的步骤分三方向搜索,记录步数
    Result: Accepted
****************************************************************/


#define INF 0x3f3f3f3f
#define MINN -0x3f3f3f3f
#define MAXN 0x3f3f3f3f
#define MOD 10007
#define NUM 1000002

int n,k;
int step[NUM];
bool vis[NUM];
int head,next;
queue<int> q;

int bfs()
{
    memset(step,0,sizeof(step));
    memset(vis,false,sizeof(vis));
    while(!q.empty()) q.pop();

    head=n;
    q.push(head);
    step[head]=0;
    vis[head]=true;
    while(!q.empty())
    {
        head=q.front();q.pop();
        for(int i=0;i<3;i++)
        {
            if(i==0) next=head-1;
            else if(i==1) next=head+1;
            else next=head*2;
            if(next<0 || next>=NUM) continue;
            if(!vis[next])
            {
                q.push(next);
                vis[next]=true;
                step[next]=step[head]+1;
            }
            if(next==k) return step[next];
        }
    }
}

int main()
{
    //freopen("poj.in","r",stdin);
    //freopen("out.out","w",stdout);

    while(scanf("%d%d",&n,&k)!=EOF)
    {
        if(n>k) printf("%d
",n-k);
        else printf("%d
",bfs());
    }

    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/wygdove/p/4814324.html