#P8092. [USACO22JAN] Drought B

[USACO22JAN] Drought B

Problem Description

The grass in Farmer John’s pasture has all dried up in a severe drought. After hours of despair and thinking, Farmer John comes up with a brilliant idea: buy corn to feed his precious cows.

FJ has NN cows (1N1051 \leq N \leq 10^5) standing in a line. The ii-th cow in the line has hunger level hih_i (0hi1090 \leq h_i \leq 10^9). Since cows are social animals, they insist on eating together. The only way for FJ to decrease the cows’ hunger levels is to choose two adjacent cows ii and i+1i+1 and feed each of them one bag of corn, which decreases both of their hunger levels by 11.

FJ wants to feed his cows until all cows have the same non-negative hunger level. Please help FJ find the minimum number of bags of corn needed to reach this state, or output 1-1 if it is impossible.

Input Format

Each test contains multiple independent subtasks, and all of them must be answered correctly to pass the entire test.

The first line of input contains TT (1T1001 \le T \le 100), the number of subtasks you need to solve.

Then follow TT subtasks. Each subtask contains two lines.

The first line contains NN, and the second line contains h1,h2,,hNh_1,h_2,\ldots,h_N. The input guarantees that the sum of NN over all subtasks does not exceed 10510^5.

The value of NN may be different for each subtask.

Output Format

Output TT lines, one line for each subtask.

5
3
8 10 5
6
4 6 4 4 6 4
3
0 1 0
2
1 2
3
10 9 9
14
16
-1
-1
-1

Hint

Sample Explanation.

For the first subtask, feed cows 22 and 33 two bags of corn each, then feed cows 11 and 22 five bags of corn each. This makes all cows have hunger level 33.

For the second subtask, feed cows 11 and 22 two bags of corn each, cows 22 and 33 two bags each, cows 44 and 55 two bags each, and cows 55 and 66 two bags each. This makes all cows have hunger level 22.

For the remaining subtasks, it is impossible to make the cows’ hunger levels equal.

Constraints.

  • For all subtasks in test point 2, N3N \leq 3 and hi100h_i \le 100.

  • For all subtasks in test points 3-8, N100N \le 100 and hi100h_i \le 100.

  • For all subtasks in test points 9-14, N100N \le 100.

  • Test point 15 has no additional constraints.

  • In addition, in test points 3-5 and 9-11, NN is even, and in test points 6-8 and 12-14, NN is odd.

Translated by ChatGPT 5