306810: CF1254B2. Send Boxes to Alice (Hard Version)

Memory Limit:256 MB Time Limit:1 S
Judge Style:Text Compare Creator:
Submit:0 Solved:0

Description

Send Boxes to Alice (Hard Version)

题意翻译

$n$盒排成一列的糖果盒,每次可以取出某一盒一颗糖果放到相邻的糖果盒里 问使得所有盒子的里的糖果数均能被某个$k(k>1)$整除的最少移动次数

题目描述

This is the harder version of the problem. In this version, $ 1 \le n \le 10^6 $ and $ 0 \leq a_i \leq 10^6 $ . You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare $ n $ boxes of chocolate, numbered from $ 1 $ to $ n $ . Initially, the $ i $ -th box contains $ a_i $ chocolate pieces. Since Bob is a typical nice guy, he will not send Alice $ n $ empty boxes. In other words, at least one of $ a_1, a_2, \ldots, a_n $ is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer $ k > 1 $ such that the number of pieces in each box is divisible by $ k $ . Note that Alice won't mind if there exists some empty boxes. Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box $ i $ and put it into either box $ i-1 $ or box $ i+1 $ (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.

输入输出格式

输入格式


The first line contains a single integer $ n $ ( $ 1 \le n \le 10^6 $ ) — the number of chocolate boxes. The second line contains $ n $ integers $ a_1, a_2, \ldots, a_n $ ( $ 0 \le a_i \le 10^6 $ ) — the number of chocolate pieces in the $ i $ -th box. It is guaranteed that at least one of $ a_1, a_2, \ldots, a_n $ is positive.

输出格式


If there is no way for Charlie to make Alice happy, print $ -1 $ . Otherwise, print a single integer $ x $ — the minimum number of seconds for Charlie to help Bob make Alice happy.

输入输出样例

输入样例 #1

3
4 8 5

输出样例 #1

9

输入样例 #2

5
3 10 2 1 5

输出样例 #2

2

输入样例 #3

4
0 5 15 10

输出样例 #3

0

输入样例 #4

1
1

输出样例 #4

-1

说明

In the first example, Charlie can move all chocolate pieces to the second box. Each box will be divisible by $ 17 $ . In the second example, Charlie can move a piece from box $ 2 $ to box $ 3 $ and a piece from box $ 4 $ to box $ 5 $ . Each box will be divisible by $ 3 $ . In the third example, each box is already divisible by $ 5 $ . In the fourth example, since Charlie has no available move, he cannot help Bob make Alice happy.

Input

题意翻译

$n$盒排成一列的糖果盒,每次可以取出某一盒一颗糖果放到相邻的糖果盒里 问使得所有盒子的里的糖果数均能被某个$k(k>1)$整除的最少移动次数

加入题单

算法标签: