#P16920. [JLCPC 2026] 翻转逆序对

    ID: 19238 远端评测题 1500ms 1024MiB 尝试: 0 已通过: 0 显示难度普及+/提高− 上传者: 标签>数学吉林O2优化枚举前缀和2026省赛/邀请赛

[JLCPC 2026] 翻转逆序对

Problem Description

tarjen\mathit{tarjen} has a permutation pp of length nn. You may perform the following operation at most once: choose two integers ll and rr (1lrn1 \le l \le r \le n), and reverse the subarray pl,pl+1,,prp_l, p_{l+1}, \ldots, p_r.

The smart tarjen\mathit{tarjen} wants to test you: what is the maximum number of inversions in the permutation after the operation?

An inversion is defined as a pair of indices (i,j)(i, j) such that 1i<jn1 \le i < j \le n and pi>pjp_i > p_j.

Input Format

The first line contains an integer TT (1T1051 \le T \le 10^5), indicating the number of test cases. Then follow TT blocks, each describing one test case. For each test case:

  • The first line contains an integer nn (1n80001 \le n \le 8000), the length of the permutation.
  • The second line contains nn integers p1,p2,,pnp_1, p_2, \ldots, p_n (1pin1 \le p_i \le n), representing the given permutation.

The testdata guarantees that n8000\sum n \le 8000.

Output Format

For each test case, output one integer per line, representing the maximum number of inversions.

3
3
2 1 3
5
5 4 3 2 1
6
3 5 1 4 2 6
2
10
10

Hint

In the first test case, reversing the interval [1,3][1, 3] yields [3,1,2][3, 1, 2], which has 22 inversions: (1,2)(1,2) and (1,3)(1,3).

In the second test case, you may choose not to perform any operation. The original permutation is [5,4,3,2,1][5,4,3,2,1], which has 1010 inversions. This is the maximum number of inversions achievable by a permutation of length 55.

In the third test case, reversing the interval [3,6][3, 6] yields [3,5,6,2,4,1][3, 5, 6, 2, 4, 1], which has 1010 inversions: (1,4)(1,4), (1,6)(1,6), (2,4)(2,4), (2,5)(2,5), (2,6)(2,6), (3,4)(3,4), (3,5)(3,5), (3,6)(3,6), (4,6)(4,6), and (5,6)(5,6).

Translated by ChatGPT 5