#P17473. [ICPC 2018 Jiaozuo R] Can You Solve the Harder Problem?

    ID: 19940 远端评测题 6000ms 512MiB 尝试: 0 已通过: 0 显示难度省选/NOI− 上传者: 标签>2018线段树后缀自动机 SAM后缀数组 SAICPC单调栈

[ICPC 2018 Jiaozuo R] Can You Solve the Harder Problem?

Problem Description

You are given a sequence a\mathbf{a} denoted by (a1,a2,⋯ ,an)(a_1, a_2, \cdots, a_n). A query with 1≤l≤r≤n1 \leq l \leq r \leq n is defined as

$$\displaystyle Q_{max}(l, r) = \max \lbrace a_l, a_{l + 1}, \cdots, a_r \rbrace .$$

An easy problem may ask you to calculate the sum of answers for all queries with integers 1≤l≤r≤n1 \leq l \leq r \leq n, but we would like to show you a harder one.

Define a classifier as a container that stores unique elements. Each element in the classifier has two values, named the key value and the mapped value. The key value of each element is a consecutive subsequence of a\mathbf{a} and the mapped value of that element is an integer indicating the maximum value in the subsequence. The classifier only stores elements with distinct key values, which means extra duplicated elements (with the same key value) would be removed from the classifier.

Denote S(l,r)S(l, r) as (al,al+1,⋯ ,ar)(a_l, a_{l + 1}, \cdots, a_r), a consecutive subsequence of a\mathbf{a} meeting the condition that ll and rr are integers with 1≤l≤r≤n1 \leq l \leq r \leq n. Now we intend to use a classifier CA\mathbf{CA} to store all the consecutive subsequences S(l,r)S(l, r) of a\mathbf{a} with their Qmax(l,r)Q_{max}(l, r). You are asked to determine the sum of mapped values in CA\mathbf{CA}.

Actually, what we defined above is a map of the form map<vector<int>, int> in C++ or Map<ArrayList<Integer>, Integer> in Java, so if you are seasoned using these data structures, you may realize that what we intend to do is to insert all possible elements (S(l,r),Qmax(l,r))(S(l, r), Q_{max}(l, r)) with integers 1≤l≤r≤n1 \leq l \leq r \leq n into the classifier CA\mathbf{CA} and then ask you to calculate the sum of mapped values in it.

Input Format

The input contains several test cases, and the first line contains a positive integer TT indicating the number of test cases which is up to 10001000.

For each test case, the first line contains an integer nn indicating the number length of the given sequence a\mathbf{a}, where 1≤n≤2×1051 \leq n \leq 2 \times 10^5.

The second line contains nn positive integers a1,a2,⋯ ,ana_1, a_2, \cdots, a_n describing the sequence a\mathbf{a}, where 1≤ai≤1061 \leq a_i \leq 10^6.

We guarantee that there are at most 1010 test cases with n>1000n > 1000.

Output Format

For each test case, output a line containing the sum of mapped values in CA\mathbf{CA}.

2
3
1 2 3
3
2 3 3
14
14

Hint

In the first sample case, the sum of mapped values in CA\mathbf{CA} is equal to 1+2+3+2+3+31 + 2 + 3 + 2 + 3 + 3.

In the second sample case, the sum of mapped values in CA\mathbf{CA} is equal to 2+3+3+3+32 + 3 + 3 + 3 + 3.