PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#QHD0000039. Chuyển chỗ ngồi (Armchairs)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Chuyển chỗ ngồi (Armchairs)

Armchairs

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

There are nn armchairs in a row, numbered 11 to nn. Each chair initially holds exactly one person (ai=1a_i=1) or is empty (ai=0a_i=0). The number of occupied chairs does not exceed half the total.

You may ask a person in an occupied chair ii to move to a currently empty chair jj. This operation costs ∣i−j∣|i-j| minutes. Operations take place sequentially, not simultaneously, and you may perform as many as needed.

The goal is that every chair that was initially occupied becomes empty. Find the minimum total time needed. If no chair is occupied initially, the answer is 00.

Input

The first line contains nn. The second line contains nn values a1,…,ana_1,\ldots,a_n, each equal to 00 or 11.

Output

Print one integer: the minimum total time, in minutes.

Subtasks

  • Subtask 1 (20 points): 2≤n≤302\le n\le 30; ai∈{0,1}a_i\in\{0,1\}; ∑iai≤⌊n/2⌋\sum_i a_i\le\lfloor n/2\rfloor.
  • Subtask 2 (30 points): 2≤n≤6002\le n\le 600; ai∈{0,1}a_i\in\{0,1\}; ∑iai≤⌊n/2⌋\sum_i a_i\le\lfloor n/2\rfloor.
  • Subtask 3 (50 points): 2≤n≤50002\le n\le 5000; ai∈{0,1}a_i\in\{0,1\}; ∑iai≤⌊n/2⌋\sum_i a_i\le\lfloor n/2\rfloor.

Examples

Input

7
1 0 0 1 0 0 1

Output

3

Explanation

The initially occupied seats are 1,4,71,4,7; free seats are 2,3,5,62,3,5,6. Move the people from 11 to 22, from 44 to 55, and from 77 to 66. Each move costs 11 minute. All initially occupied chairs become empty, and the total of 1+1+1=31+1+1=3 minutes is minimum.