We can consider the positions on the number line as vertices of a graph, and the possible movements as edges of this graph. For example, a step to the right represents an edge between vertices and x + 1, while teleportation represents an edge between and 2 * x.
The minimum number of minutes it takes for Farmer John to catch the escaped cow corresponds to the length of the shortest path between vertices and . To find this path, we use a breadth-first search starting from vertex . The answer is the shortest distance to vertex .
Example
Let’s look at the fastest route Farmer John can take to reach the cow: 5 → 10 → 9 → 18 → 17. This takes minutes.
Let’s now examine the step-by-step filling of the shortest distance array .
Algorithm implementation
Declare the array to store the shortest distances and a queue to perform the breadth-first search.
#define MAX 200001
int dist[MAX];
queue<int> q;The go function handles the transition from vertex to vertex . If dist[to] \ne -1, it means that the vertex to has already been visited, and there is no need to visit it again.
void go(int v, int to)
{
if (dist[to] != -1) return;If the vertex is not visited yet, add it to the queue and update the value of dist[to] by adding one to the distance from vertex .
q.push(to);
dist[to] = dist[v] + 1;
}The function bfs implements a breadth-first search starting from the vertex .
void bfs(int start)
{Initialize the data necessary for the breadth-first search.
memset(dist, -1, sizeof(dist));
dist[start] = 0;
q.push(start);Start the main loop, which continues until the queue becomes empty.
while (!q.empty())
{Extract vertex from the front of the queue.
int x = q.front(); q.pop();If the position , where the cow is located, is reached, terminate the search.
if (x == k) return;Consider all possible moves — to the right, to the left, and teleportation. If a move is possible, update the corresponding arrays.
if (x + 1 < MAX) go(x, x + 1);
if (x - 1 >= 0) go(x, x - 1);
if (2 * x < MAX) go(x, 2 * x);
}
}The main part of the program. Read the input data. Run a breadth-first search starting from position . Print the answer — the minimum number of minutes it takes for Farmer John to reach position .
scanf("%d %d", &n, &k);
bfs(n);
printf("%d\n", dist[k]);