博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Poj 3287 Catch That Cow(BFS)
阅读量:5098 次
发布时间:2019-06-13

本文共 2235 字,大约阅读时间需要 7 分钟。

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.
题意:在一维的直线上,给出John的位置n,和cow的位置k,求出John按照给定三种规则找到cow的最少步数。
分析:用广度优先搜索从源点开始,依次用三种规则进行查找,设置边界条件,最先找到的即为最优解。这里还要注意下数组边界大小要比用于比较的边界要大一点,否则会数组越界而RE,我在这里吃了6个RE,一直没找到原因。后来才惊奇地发现时用于比较的MAX和数组大小Max相同。
import java.util.LinkedList;import java.util.Scanner;public class Main {	static int start, end;	static int MAX = 200000;	static LinkedList
q; static boolean[] visited; static int[] step; static int t, next; static int bfs() { q.add(start); visited[start] = true; step[start] = 0; while (!q.isEmpty()) { t = q.poll(); for (int i = 0; i < 3; i++) { if (i == 0) { next = t - 1; } else if (i == 1) { next = t + 1; } else { next = t * 2; } if (next > MAX || next < 0) continue; if (!visited[next]) { q.add(next); step[next] = step[t] + 1; visited[next] = true; } if (next == end) return step[next]; } } return -1; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); q = new LinkedList
(); //在这个地方比MAX多加上5,放在RE visited = new boolean[MAX+5]; step = new int[MAX+5]; start = sc.nextInt(); end = sc.nextInt(); if (start >= end) { System.out.println(start - end); } else { System.out.println(bfs()); } }}

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

转载于:https://www.cnblogs.com/AndyDai/p/4734096.html

你可能感兴趣的文章
type convert in python
查看>>
关键字参数
查看>>
Python Cookbook(第2版)中文版
查看>>
TCP协议栈的6类定时器
查看>>
【图论 动态规划拆点】luoguP3953 逛公园
查看>>
【大话存储II】学习笔记(2章), SSD
查看>>
SQLHelp sql数据库的DAL
查看>>
阅读学术论文的心得体会from小木虫
查看>>
Python——Message控件
查看>>
多线程下单例模式:懒加载(延迟加载)和即时加载
查看>>
从 fn_dbLog 解析操作日志(补充update)
查看>>
JavaEE 数据库随机值插入测试
查看>>
this
查看>>
判断对象类型 type()
查看>>
Php函数之end
查看>>
腾讯AB题
查看>>
C# 实现冒泡算法--不一定效率,但很容易理解
查看>>
如何开发AR增强现实应用与产品
查看>>
C++中遍历lua table
查看>>
Python 编程快速上手 第 7章 模式匹配与正则表达式
查看>>