Rope Folding
InterviewTime limit1sMemory limit128 MB
Given knots at integer positions on a rope, count the fold points where every knot in the overlapping interval mirrors onto another knot.
- Level
Medium4 of 10
- Topics
- Array, Brute force, Implementation, Geometry
- Solved
- No attempts yet
Problem
Farmer John has a rope of length () that he uses for tasks around his farm. The rope has knots () tied into it at distinct integer positions, including one knot at each of its two endpoints (positions and ).
FJ can fold the rope back onto itself at certain points. When he folds at a point, one side of the rope reflects over onto the other side and the two strands overlap. A fold is good if, wherever the two strands lie on top of each other, every knot on one strand lines up exactly with a knot on the other strand.
Formally, a fold at position () reflects a knot at position to position . Let the shorter side have length ; the two strands then overlap on the interval . The fold is good if, for every knot inside that overlap interval, its mirror position is also a knot.
Folding exactly at a knot is allowed, but folding at either endpoint is not. Extra knots on the longer side of the fold — outside the overlap interval — do not matter. FJ only ever makes a single fold at a time.
Count the number of positions at which FJ can make a good fold.
Input
- Line 1: Two space-separated integers, and .
- Lines : Each line contains one integer in the range , the position of a single knot. Two of these positions are always and .
Output
- Line 1: A single integer — the number of positions at which a good fold can be made.
Hint
For example, if the rope has length with knots at , the four good fold positions are and :
- Fold at : the overlap is ; knots and mirror onto each other.
- Fold at : the overlap is ; knots are symmetric about .
- Fold at : the overlap is ; knots are symmetric about .
- Fold at : the overlap is ; knots and mirror onto each other (the extra knots sit on the longer side and are ignored).
A fold position may be a half-integer: since the endpoint knot on the shorter side must reflect onto an integer knot, every good fold occurs where is an integer.