#P17294. [ICPC 2026 Xi'an I] North and South

    ID: 17185 Type: RemoteJudge 1000ms 512MiB Tried: 0 Accepted: 0 Difficulty: 6 Uploaded By: Tags>贪心差分ICPC2026省赛/邀请赛西安

[ICPC 2026 Xi'an I] North and South

题目描述

Yuki has a sequence aa of length nn.

Yuki defines an operation as follows:

  • Choose an interval [l,r][l, r] of even length\textbf{even length}. For every integer ii such that l≤i≤rl \le i \le r:
    • If i−li-l is odd, the value of aia_i decreases by 11, i.e., ai←ai−1a_i \gets a_i-1.
    • If i−li-l is even, the value of aia_i increases by 11, i.e., ai←ai+1a_i \gets a_i+1.

Now, Yuki wants to perform some number of operations such that all numbers in the sequence aa are equal. You need to help Yuki find the minimum number of operations required to make all numbers in the sequence aa equal, or report if it is impossible.

输入格式

This problem contains multiple test cases.

The first line contains a positive integer tt (1≤t≤105)(1 \le t \le 10^5), representing the number of test cases.

For each test case:

  • The first line contains a positive integer nn (1≤n≤106)(1 \le n \le 10^6).
  • The second line contains nn integers a1,…,ana_1, \dots, a_n (0≤ai≤1012)(0 \le a_i \le 10^{12}).

It is guaranteed that the sum of nn over all test cases does not exceed 10610^6.

输出格式

For each test case, output one line:

  • If it is impossible, output −1-1.
  • If it is possible, output an integer representing the minimum number of operations to make all numbers in the sequence aa equal.
3
2
1 3
4
1 5 1 5
5
1 3 1 3 1
1
2
-1

提示

For the first test case:

  • Perform the operation on the interval [1,2][1, 2]. The sequence becomes 2,22, 2, where all numbers are equal.
  • It can be proven that no solution with fewer operations exists, so the answer is 11.

For the second test case:

  • Perform the operation on the interval [1,4][1, 4]. The sequence becomes 2,4,2,42, 4, 2, 4.
  • Perform the operation on the interval [1,4][1, 4]. The sequence becomes 3,3,3,33, 3, 3, 3, where all numbers are equal.
  • It can be proven that no solution with fewer operations exists, so the answer is 22.

For the third test case:

  • It is easy to prove that it is impossible to make all numbers equal regardless of the number of operations, so the answer is −1-1.