POJ3278 Catch That Cow题解 广度优先搜索+限定解空间

来源:互联网 发布:mysql 查看版本号 编辑:程序博客网 时间:2024/06/05 23:41

题目大意:直线上的两个坐标N和K,其中从N出发到达K,可以变换为+1、-1或者*2,每变换一次坐标,需要花费一分钟,求最短时间到达K。

分析:由于要求最优解,我们首先考虑使用BFS,相当于每次入队要花费一分钟,所以通过BFS到达K的时候,就是最优解。但是注意这题需要限定新加入队列进行下一轮搜索的节点的坐标,因为题目中要求是0-100000,所以进行控制,如果不进行控制的话,那么可以无限扩大,以至于爆掉空间也有可能获取不到最优解。

代码:

import java.util.*;import java.io.*;public class Main {static final int maxn = 100005;static int n, k;static int ans;static ArrayDeque<Node> que = new ArrayDeque<Node>();static boolean vis[] = new boolean[maxn];public static int bfs() {que.clear();Arrays.fill(vis, false);que.addLast(new Node(n, 0));vis[n] = true;while(!que.isEmpty()) {Node temp = que.pollFirst();if(temp.x == k) {return temp.t;}if(temp.x + 1 >= 0 && temp.x + 1 < maxn && !vis[temp.x + 1]) {vis[temp.x + 1] = true;que.addLast(new Node(temp.x + 1, temp.t + 1));}if(temp.x - 1 >= 0 && temp.x - 1 < maxn && !vis[temp.x - 1]) {vis[temp.x - 1] = true;que.addLast(new Node(temp.x -1, temp.t + 1));}if(temp.x * 2 >= 0 && temp.x * 2 < maxn && !vis[temp.x * 2]) {vis[temp.x * 2] = true;que.addLast(new Node(temp.x * 2, temp.t + 1));}}return -1;}public static void main(String[] args) {InputReader in = new InputReader(System.in);PrintWriter out = new PrintWriter(System.out);n = in.nextInt();k = in.nextInt();ans = bfs();out.println(ans);out.close();}static class Node {int x, t;public Node() {}public Node(int x, int t) {this.x = x;this.t = t;}}static class InputReader {public BufferedReader reader;public StringTokenizer tokenizer;public InputReader(InputStream stream) {reader = new BufferedReader(new InputStreamReader(stream), 32768);tokenizer = null;}public String next() {try {while(tokenizer == null || !tokenizer.hasMoreTokens()) {tokenizer = new StringTokenizer(reader.readLine());} } catch (IOException e) {throw new RuntimeException(e);}return tokenizer.nextToken();}public int nextInt() {return Integer.parseInt(next());}public long nextLong() {return Long.parseLong(next());}}}