Archive

BOJ. Hide And Sick(4) (13913)

Archived technical note: BOJ. Hide And Sick(4) (13913).

Problem link

For each position x in the inclusive range [0, 100000], the allowed moves are x - 1, x + 1, and 2 * x, provided the result remains in the range. Every move costs one second, so breadth-first search visits positions in nondecreasing order of the number of moves from the start. The first time a position is discovered, its distance is therefore minimal; recording the position that discovered it as its parent also records a shortest path.

The start is enqueued once with distance zero. Each newly discovered in-range position is marked immediately before enqueueing, which prevents duplicate queue entries and cycles (including the self-transition 0 -> 0). When the target is reached, follow parent links from target back to start and reverse that chain. This gives the exact shortest-path length and lists positions in travel order. The search and reconstruction take O(R) time and space, where R = 100001 is the number of positions.

import java.io.*;
import java.util.*;

public class Main {
  public static void main(String[] args) throws IOException {
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer values = new StringTokenizer(input.readLine());
    int start = Integer.parseInt(values.nextToken());
    int target = Integer.parseInt(values.nextToken());

    int range = 100001;
    int[] distance = new int[range];
    int[] parent = new int[range];
    int[] queue = new int[range];
    for (int i = 0; i < range; i++) {
      distance[i] = -1;
      parent[i] = -1;
    }

    int front = 0;
    int back = 0;
    queue[back++] = start;
    distance[start] = 0;

    while (front < back && distance[target] == -1) {
      int current = queue[front++];
      int nextDistance = distance[current] + 1;

      if (current > 0 && distance[current - 1] == -1) {
        distance[current - 1] = nextDistance;
        parent[current - 1] = current;
        queue[back++] = current - 1;
      }
      if (current < 100000 && distance[current + 1] == -1) {
        distance[current + 1] = nextDistance;
        parent[current + 1] = current;
        queue[back++] = current + 1;
      }
      int doubled = current * 2;
      if (doubled <= 100000 && distance[doubled] == -1) {
        distance[doubled] = nextDistance;
        parent[doubled] = current;
        queue[back++] = doubled;
      }
    }

    int[] path = new int[distance[target] + 1];
    int length = path.length;
    int position = target;
    for (int i = length - 1; i >= 0; i--) {
      path[i] = position;
      if (i > 0) {
        position = parent[position];
      }
    }

    StringBuilder output = new StringBuilder();
    output.append(distance[target]).append('\n');
    for (int value : path) {
      output.append(value).append(' ');
    }
    System.out.println(output);
  }
}