#P15541. [CCC 2026 S1] Baby Hop, Giant Hop

[CCC 2026 S1] Baby Hop, Giant Hop

Description

Samantha the Frog is hopping between lily pads arranged in a straight line, evenly spaced. There are an infinite number of lily pads. The lily pads are numbered, in order, using integers. For every integer, there is also a lily pad.

Samantha starts on a lily pad numbered AA and would like to hop onto a lily pad numbered BB. She can take a giant hop of length KK, or a baby hop of length 1. Each hop can be either forwards or backwards.

Samantha would like to know the fewest number of hops needed to get from AA to BB. But sometimes, she would like to know the second fewest number of hops needed.

Input Format

The first line of input contains a single integer, AA, the starting lily pad (1018A1018-10^{18} \le A \le 10^{18}).

The second line of input contains a single integer, BB, the ending lily pad (1018B1018-10^{18} \le B \le 10^{18}).

The third line of input contains a single integer, KK, the distance of a giant hop (2K10182 \le K \le 10^{18}).

The fourth line of input contains the integer, TT, which is either 1 or 2, indicating if the fewest (when T=1T = 1) or second fewest (when T=2T = 2) number of steps should be found.

Output Format

On a single line, output:

  • the fewest number of hops, if T=1T = 1
  • the second fewest number of hops, if T=2T = 2

required to move from lily pad AA to lily pad BB.

0
10
3
1
4
0
11
4
1
4
0
11
4
2
5
0
0
3
1
0

Hint

Explanation of Output for Sample Input 1

Samantha hops to lily pads labeled 33, 66, and 99, with three giant hops, and then hops to the lily pad labeled 1010 with one baby hop.

Explanation of Output for Sample Input 2

Samantha hops to lily pads labeled 44, 88, and 1212, with three giant hops, and then hops to the lily pad labeled 1111 with one (backwards) baby hop.

Explanation of Output for Sample Input 3

The fewest number of hops needed (44) was found in Sample 2. In this input, the second fewest number of steps is to be found, since T=2T = 2. Samantha hops to lily pads labeled 44 and 88 with two giant hops, and then hops to the lily pad labeled 1111 with three baby hops.

The following table shows how the 15 available marks are distributed:

Marks Awarded Bounds on A,BA, B Bounds on KK Bounds on TT Additional Restrictions
5 marks 0A,B100 \le A, B \le 10 K=2K = 2 T=1T = 1 Only hops in the positive direction needed
6 marks 1018A,B1018-10^{18} \le A, B \le 10^{18} 2K10182 \le K \le 10^{18} None
2 marks 0A,B1000 \le A, B \le 100 2K42 \le K \le 4 T=1T = 1 or T=2T = 2
1018A,B1018-10^{18} \le A, B \le 10^{18} 2K10182 \le K \le 10^{18}

Note that for full marks, solutions will need to handle 64-bit integers. For example:

  • in C/C++, the type long long should be used;
  • in Java, the type long should be used.