Hide

Problem F
Circle Merge

Languages en sv

Emil has $N$ bags of stones placed in a circle. Each bag contains some number of stones, where the number of stones in bag $i$ is $a_i$ for $1 \leq i \leq N$. The bags are arranged in a circle, such that bag $1$ is adjacent to bags $2$ and $N$, bag $2$ is adjacent to bags $1$ and $3$, $\dots $, and bag $N$ is adjacent to bags $N-1$ and $1$.

Emil wants all bags to contain the same number of stones. In one move, Emil can merge two adjacent bags into a single bag containing the sum of the stones from the two original bags.

What is the minimum number of moves required to make all bags contain the same number of stones?

Input

The first line contains an integer $N$ ($1 \le N \le 2 \cdot 10^5$), the number of bags in the circle initially.

The second line contains $N$ integers $a_1, a_2, \ldots , a_N$ ($1 \le a_i \le 5 \cdot 10^{12}$), where $a_i$ is the number of stones in bag $i$.

Output

Print a single integer, the minimum number of moves required to make all bags contain the same number of stones.

Scoring

Your solution will be tested on a set of test groups, each worth a number of points. Each test group contains a set of test cases. To get the points for a test group you need to solve all test cases in the test group.

Group

Points

Constraints

$1$

$4$

There exist a solution with the minimum number of moves, where the number of stones in every bag is $a_1$.

$2$

$15$

$N \le 100$

$3$

$22$

$N \le 3000, a_i \le 200$

$4$

$29$

$a_i \le 200$

$5$

$30$

No additional constraints.

Explanation of Sample 1

In the first case, it is optimal to merge the bags as follows:

  • Merge the last and the first bag: [1, 2, 3, 4, 5] $\to $ [6, 2, 3, 4] (note that the bags are arranged in a circle)

  • Merge the first and second bag: [6, 2, 3, 4] $\to $ [8, 3, 4]

  • Merge the second and third bag: [8, 3, 4] $\to $ [8, 7]

  • Merge the last two bags: [8, 7] $\to $ [15].

In total, 4 moves are required for all bags to contain the same number of stones. It can be shown that it is not possible to do this in fewer moves.

Explanation of Sample 2

In the second case, it is optimal to merge the bags as follows:

  • Merge bags 4 and 5: [5, 2, 3, 1, 4, 2, 1, 1, 1] $\to $ [5, 2, 3, 5, 2, 1, 1, 1]

  • Merge bags 6 and 7: [5, 2, 3, 5, 2, 1, 1, 1] $\to $ [5, 2, 3, 5, 2, 2, 1]

  • Merge bags 7 and 8: [5, 2, 3, 5, 2, 2, 1] $\to $ [5, 2, 3, 5, 2, 3]

  • Merge bags 2 and 3: [5, 2, 3, 5, 2, 3] $\to $ [5, 5, 5, 2, 3]

  • Merge bags 4 and 5: [5, 5, 5, 2, 3] $\to $ [5, 5, 5, 5].

In total, 5 moves are required for all bags to contain the same number of stones. It can be shown that it is not possible to do this in fewer moves.

Sample Input 1 Sample Output 1
5
1 2 3 4 5
4
Sample Input 2 Sample Output 2
9
5 2 3 1 4 2 1 1 1
5

Please log in to submit a solution to this problem

Log in