#P6616. Minimal Moves to Dismantle n-Chain Puzzle
Minimal Moves to Dismantle n-Chain Puzzle
Minimal Moves to Dismantle n-Chain Puzzle
You are given an n‐chain puzzle which has the same structure as the traditional nine-link chain (as shown in the image below). There is a long horizontal bar with n rings hanging on it; note that these rings affect each other in a prescribed manner.
The rings are numbered from 1 to n in order along the bar, with ring 1 at the head of the bar and ring n at the tail. Define fi as the state of ring i: fi = 1 means the ring is on the bar while fi = 0 means it is off the bar. A move (called a dismantle/assemble move) consists of flipping the state of a ring (i.e. 1 becomes 0, and 0 becomes 1).
The legal moves are governed by the following rules:
- Ring 1 can be flipped at any time, independently.
- For k ≥ 1, ring k+1 can be flipped individually if and only if fk = 1 and for all i < k we have fi = 0.
- If f1 = f2, then rings 1 and 2 can be flipped together in a single move.
Your task is: Given the initial state of the n-chain, compute the minimum number of moves required to completely dismantle the chain (i.e. make all fi = 0).
inputFormat
The input consists of two lines.
- The first line contains a single integer n (the number of rings).
- The second line contains n integers, each being either 0 or 1, representing the initial states f1, f2, ..., fn (1 indicates the ring is on the bar and 0 indicates it is off the bar).
outputFormat
Output a single integer: the minimum number of moves required to achieve the state where all rings are off the bar (i.e. all fi = 0).
sample
1
1
1