CF1827B2.Range Sorting (Hard Version)

普及/提高-

通过率:0%

AC君温馨提醒

该题目为【codeforces】题库的题目,您提交的代码将被提交至codeforces进行远程评测,并由ACGO抓取测评结果后进行展示。由于远程测评的测评机由其他平台提供,我们无法保证该服务的稳定性,若提交后无反应,请等待一段时间后再进行重试。

题目描述

The only difference between this problem and the easy version is the constraints on tt and nn .

You are given an array aa , consisting of nn distinct integers a1,a2,,ana_1, a_2, \ldots, a_n .

Define the beauty of an array p1,p2,pkp_1, p_2, \ldots p_k as the minimum amount of time needed to sort this array using an arbitrary number of range-sort operations. In each range-sort operation, you will do the following:

  • Choose two integers ll and rr ( 1l<rk1 \le l < r \le k ).
  • Sort the subarray pl,pl+1,,prp_l, p_{l + 1}, \ldots, p_r in rlr - l seconds.

Please calculate the sum of beauty over all subarrays of array aa .

A subarray of an array is defined as a sequence of consecutive elements of the array.

输入格式

Each test contains multiple test cases. The first line contains the number of test cases tt ( 1t1041 \le t \le 10^4 ). The description of the test cases follows.

The first line of each test case contains a single integer nn ( 1n31051 \le n \le 3 \cdot 10^5 ) — the length of the array aa .

The second line of each test case consists of nn integers a1,a2,,ana_1,a_2,\ldots, a_n ( 1ai1091\le a_i\le 10^9 ). It is guaranteed that all elements of aa are pairwise distinct.

It is guaranteed that the sum of nn over all test cases does not exceed 31053 \cdot 10^5 .

输出格式

For each test case, output the sum of beauty over all subarrays of array aa .

输入输出样例

  • 输入#1

    5
    2
    6 4
    3
    3 10 6
    4
    4 8 7 2
    5
    9 8 2 4 6
    12
    2 6 13 3 15 5 10 8 16 9 11 18

    输出#1

    1
    2
    8
    16
    232

说明/提示

In the first test case:

  • The subarray [6][6] is already sorted, so its beauty is 00 .
  • The subarray [4][4] is already sorted, so its beauty is 00 .
  • You can sort the subarray [6,4][6, 4] in one operation by choosing l=1l = 1 and r=2r = 2 . Its beauty is equal to 11 .

The sum of beauty over all subarrays of the given array is equal to 0+0+1=10 + 0 + 1 = 1 .In the second test case:

  • The subarray [3][3] is already sorted, so its beauty is 00 .
  • The subarray [10][10] is already sorted, so its beauty is 00 .
  • The subarray [6][6] is already sorted, so its beauty is 00 .
  • The subarray [3,10][3, 10] is already sorted, so its beauty is 00 .
  • You can sort the subarray [10,6][10, 6] in one operation by choosing l=1l = 1 and r=2r = 2 . Its beauty is equal to 21=12 - 1 = 1 .
  • You can sort the subarray [3,10,6][3, 10, 6] in one operation by choosing l=2l = 2 and r=3r = 3 . Its beauty is equal to 32=13 - 2 = 1 .

The sum of beauty over all subarrays of the given array is equal to 0+0+0+0+1+1=20 + 0 + 0 + 0 + 1 + 1 = 2 .

首页