Table of Contents

ExplanationImplementation

Official Analysis (C++)

Explanation

At each step, we check where Farmer John starts and where he's trying to go. If his path doesn't overlap with Bessie's path, we add the distance he covers to a running total and move him to his starting position. On the other hand, if his path somehow overlaps with Bessie's, we add only his distance from Bessie to the total.

Implementation

Time Complexity: O(logxy)\mathcal{O}(\log|x - y|)

Proof

with open("lostcow.in") as read:
x, y = [int(i) for i in read.readline().split()]
dir_ = 1
total_distance = 0
dir_distance = 1
while True:
if (dir_ == 1 and x <= y and y <= (x + dir_distance)) or (
dir_ == -1 and y <= x and (x - dir_distance <= y)
):

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!