Chain
Time limit3sMemory limit512 MB
Given which rings of a bytish chain are on a bar, find the minimum number of legal put-on/take-off moves to remove all rings.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Recursion, Bit manipulation, Math
- Solved
- No attempts yet
Problem
Byteland was not always a democratic country; its history has dark chapters too. One day general Bytel, commander of the junta that ruled Byteland, decided to end the long-lasting war and freed the imprisoned activists of the opposition. He had no intention, however, of releasing their leader Bytesar. Instead he chained Bytesar to the wall with a bytish chain. The chain is made of interlocking rings and a bar fixed to the wall. The rings are not attached to the bar directly, yet they are hard to slip off it.
Help Bytesar take every ring off the bar. The rings are numbered , and they may be put on or taken off the bar under the following rules:
- exactly one ring may be put on or taken off in a single move;
- ring number 1 may always be put on or taken off;
- for , ring number may be put on or taken off only when rings are all off the bar and ring number is on the bar.
Given the initial state of the chain, write a program that computes the minimal number of moves needed to take all rings off the bar.
Input
The first line contains an integer (). The second line contains integers , separated by single spaces, each equal to 0 or 1. If , ring is on the bar; if , ring is off the bar.
Output
Print, on a single line, the minimal number of moves needed to take all rings off the bar.