#GL0000347. Chuyển kẹo giữa các hộp – Bản khó (Send Boxes to Alice (Hard Version))
Bài tập thuộc lộ trình
Mục lục đề ⌄
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 candy boxes in a line, with candies in box 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 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: .
Line 2: integers .
Output
Print the minimum number of moves, or -1.
Subtasks
- Subtask 1 (20 points): , ; có ít nhất một .
- Subtask 2 (30 points): , ; có ít nhất một .
- Subtask 3 (50 points): , ; có ít nhất một .
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 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.