#P2438. [SDOI2005] 解环

[SDOI2005] 解环

Description

To help Baitesa! The rings on the chain are numbered 1,2,,n1, 2, \ldots, n. We can detach them according to the following rules:

  • At each step, you may attach or detach exactly one ring to or from the fence.
  • Ring 11 can always be attached or detached.
  • If rings 1,,k11, \ldots, k - 1 are all detached and ring kk is attached, where 1k<n1 \le k < n, then you may attach or detach ring k+1k + 1.

Write a program that, given the description of the Byte Chain, computes the minimum number of operations needed to remove all rings from the fence and outputs the result.

Input Format

The first line contains an integer nn, where 1n10001 \le n \le 1000.
The second line contains nn integers o1,o2,,ono_1, o_2, \ldots, o_n (each is 00 or 11) separated by single spaces. If oi=1o_i = 1, then the ii-th ring is attached to the fence; if oi=0o_i = 0, then the ii-th ring is not attached.

Output Format

Output a single integer: the minimum number of operations required to detach all rings from the fence.

4
1 0 1 0

6

Hint

Translated by ChatGPT 5