CCCGuide

Problem S1: Baby Hop, Giant Hop

2026 · S1 · Original problem · DMOJ

Problem 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 11. 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 Specification

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

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

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

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

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

MarksBounds
on AA, BB
Bounds
on KK
Bounds
on TT
Additional
Restrictions
550≤A,B≤100 \le A, B \le 10K=2K=2T=1T=1Only hops in the positive direction needed
66−1018≤A,B≤1018-10^{18} \leq A, B \leq 10^{18}2≤K≤10182 \leq K \leq 10^{18}T=1T=1None
220≤A,B≤1000 \le A, B\le 1002≤K≤42 \le K\leq4T=1T=1 or T=2T=2None
22−1018≤A,B≤1018-10^{18} \leq A, B \leq 10^{18}2≤K≤10182 \leq K\leq 10^{18}T=1T=1 or T=2T=2None

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

Output Specification

On a single line, output:

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

Sample Input 1

0
10
3
1

Output for Sample Input 1

4

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.

Sample Input 2

0
11
4
1

Output for Sample Input 2

4

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.

Sample Input 3

0
11
4
2

Output for Sample Input 3

5

Explanation of Output for Sample Input 3

The fewest number of hops needed (4)(4) 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.

Sample Input 4

0
0
3
1

Output for Sample Input 4

0