Problem F

Statement
Copy Copied
F. Arctic Acquisitiontime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard output  You are given a permutation$$$^{\text{∗}}$$$ $$$a_1,a_2,\ldots,a_n$$$ of length $$$n$$$.An interval $$$[l,r]$$$ ($$$1\le l\le r\le n$$$) is jagged if and only if it contains a 21435-subsequence; that is, there exist integers $$$i_1,i_2,i_3,i_4,i_5$$$ such that $$$l\le i_1<i_2<i_3<i_4<i_5\le r$$$, and $$$a_{i_2}<a_{i_1}<a_{i_4}<a_{i_3}<a_{i_5}$$$.Your task is to calculate how many of the $$$\frac{n(n+1)}2$$$ intervals are jagged.$$$^{\text{∗}}$$$A permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array), and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array). InputEach test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le10^6$$$) — the length of the permutation.The second line of each test case contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$).It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$. OutputFor each test case, output the number of jagged subarrays.ExampleInput552 1 4 3 51010 3 5 2 1 4 9 8 6 7153 9 15 6 11 10 5 13 12 7 4 8 14 1 21210 7 12 5 4 1 2 9 3 8 6 113022 30 7 17 4 13 26 28 24 20 2 11 27 21 5 19 9 10 23 14 1 25 6 8 3 18 29 12 16 15Output10285185NoteIn the first test case, the only jagged subarray is $$$[1,5]$$$, containing $$$[2,1,4,3,5]$$$ as a subsequence.In the third test case, the subarray $$$[1,8]$$$ is jagged because it contains $$$[9,6,11,10,13]$$$ as a subsequence, which is a 21435-subsequence.