Strip
Time limit1sMemory limit128 MB
Given a strip of length n, fold it along k given creases in order and report the final length, where n can have up to 18 digits.
- Level
Medium5 of 10
- Topics
- Implementation, Simulation, Math
- Solved
- No attempts yet
Problem

Consider a strip of width , length , and negligible thickness, divided into unit squares. Starting from its left end, label each of the vertical creases with the integers to , as shown in the picture (where ). The strip may be folded only along these creases; once folded, the two overlapping parts are glued together and never straightened again.
After a fold, some labelled creases come to lie exactly on top of one another, forming a single position that therefore carries several labels. For example, folding the strip along crease makes crease and crease coincide, so from then on "" and "" denote the same crease. Folding again along crease (equivalently, along crease , which is now the same position) produces a position with three labels, .
If the fold happens to lie exactly on an end of the current strip, it changes neither the labelling nor the length. Such a fold is not forbidden; it is simply an empty fold.
A sequence of integers, each between and , therefore defines a sequence of folds. Determine the length of the strip after all folds have been applied in order.
Input
The input is given on standard input.
- Line : two space-separated positive integers and .
- Line : space-separated non-negative integers, each at most — the creases to fold along, in order.
Output
Print a single line containing one integer: the length of the strip after all folds have been applied consecutively.
Constraints
- is a positive integer with at most decimal digits.
- .
- Each fold value is an integer in the range .
Hint
For the second test case (, folds ), the positions and their labels evolve as shown below. Labels grouped in parentheses share a single position.
Start:
- fold :
- fold :
- fold :
- fold : (an empty fold — crease already sits at an end)
- fold :
Three positions remain, so the final length is .