Xsquare And Array Operations
Practice
3.8 (11 votes)
Approved
Data structures
Divide And Conquer algorithm
Hard
Open
Segment trees
Trees
Problem
51% Success 437 Attempts 50 Points 1s Time Limit 256MB Memory 1024 KB Max Code

Xsquare loves to play with arrays a lot. Today, he has an array A consisting of N distinct integers. He wants to perform following operation over his array A.

  • Select a pair of consecutive integers say (Ai,Ai+1) for some 1 ≤ i < N. Replace the selected pair of integers with the max(Ai,Ai+1).
  • Replace N with the new size of the array A.
  • Above operation incurs a cost of rupees max(Ai,Ai+1) to Xsquare.

As we can see after N-1 such operations, there is only 1 element left. Xsquare wants to know the most optimal transformation strategy to reduce the given array A to only 1 element.

A transformation strategy is considered to be most optimal if it incurs minimum cost over all possible transformation strategies.

Input

First line of input contains a single integer T denoting the number of test cases. First line of each test case starts with an integer N denoting the size of the array A. Next line of input contains N space separated integers, where ith element denotes the value Ai.

Output

For each test case, print the minimum cost required for the transformation.

Constraints

1 ≤ T ≤ 105

2 ≤ N ≤ 105

1 ≤ Ai ≤ 109

sum of N over all test case does not exceed 5*105

Subtasks

  • Subtask 1: 1 ≤ T ≤ 10 , 2 ≤ N ≤ 17 ( 20 % )
  • Subtask 2: sum of N does not exceed 5*103 ( 30 % )
  • Subtask 3: sum of N does not exceed 5*105 ( 50 % )

Warning :

Prefer to use printf / scanf instead of cin / cout .

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:50
3 votes
Tags:
ApprovedData StructuresHardSegment Trees
Points:20
132 votes
Tags:
AlgorithmsApprovedBreadth First SearchEasyGraphsMinimum spanning treeOpen
Points:50
40 votes
Tags:
ApprovedData StructuresFenwick TreeHardOpenSegment TreesTrees