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

#GL0000347. Chuyển kẹo giữa các hộp – Bản khó (Send Boxes to Alice (Hard Version))

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Chuyển kẹo giữa các hộp – Bản khó (Send Boxes to Alice (Hard Version))

Send Boxes to Alice (Hard Version)

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

There are NN candy boxes in a line, with AiA_i candies in box ii and at least one candy overall.

In one second, you may move exactly one candy from a box to one adjacent box. The target configuration must admit one common integer d>1d>1 that divides the candy count of every box; empty boxes are allowed.

Find the minimum number of adjacent moves, or -1 if no valid configuration exists.

Input

Line 1: NN.

Line 2: NN integers A1,…,ANA_1,\ldots,A_N.

Output

Print the minimum number of moves, or -1.

Subtasks

  • Subtask 1 (20 points): 1≤N≤121\le N\le12, 0≤Ai≤200\le A_i\le20; có ít nhất một Ai>0A_i>0.
  • Subtask 2 (30 points): 1≤N≤1041\le N\le10^4, 0≤Ai≤10000\le A_i\le1000; có ít nhất một Ai>0A_i>0.
  • Subtask 3 (50 points): 1≤N≤1061\le N\le10^6, 0≤Ai≤1060\le A_i\le10^6; có ít nhất một Ai>0A_i>0.

Examples

Example 1

Input

3
4 8 5

Output

9

Explanation

There are 17 candies, so choose divisor 17. Move 4 from box 1 and 5 from box 3 into box 2, costing 9 moves.

Example 2

Input

5
3 10 2 1 5

Output

2

Explanation

Move one candy from box 2 to 3 and one from box 4 to 5; the result (3,9,3,0,6)(3,9,3,0,6) is divisible by 3 everywhere.

Example 3

Input

1
1

Output

-1

Explanation

The total is 1 and has no divisor greater than 1, so the task is impossible.