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

    ID: 19704 远端评测题 1000ms 512MiB 尝试: 2 已通过: 0 显示难度普及+/提高− 上传者: 标签>贪心差分ICPC2026省赛/邀请赛西安

[ICPC 2026 Xi'an I] North and South

Problem Description

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 lirl \le i \le r:
    • If ili-l is odd, the value of aia_i decreases by 11, i.e., aiai1a_i \gets a_i-1.
    • If ili-l is even, the value of aia_i increases by 11, i.e., aiai+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.

Input Format

This problem contains multiple test cases.

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

For each test case:

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

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

Output Format

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

Hint

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.