This page is still under construction.

Parts of this page are still being built. What you see may change.

Sequence Merging

Time limit1sMemory limit128 MB

Summary
Repeatedly replace an adjacent pair with its larger value and pay that value, ordering the merges to leave the smallest total cost.
Level

Medium7 of 10

Topics
Divide and conquer, Stack, Greedy
Solved
No attempts yet

Problem

You are given a sequence a1,a2,…,ana_1, a_2, \dots, a_n. In one step you can pick two adjacent numbers aia_i and ai+1a_{i+1} and replace both of them with the single number max⁡(ai,ai+1)\max(a_i, a_{i+1}). That step costs max⁡(ai,ai+1)\max(a_i, a_{i+1}). Each step makes the sequence one shorter, so after n−1n-1 steps a single number is left.

Given the sequence, compute the minimum total cost of reducing it to length 1.

Input

The first line contains the number of test cases TT (1≤T≤1000001 \le T \le 100000).

Each test case takes two lines. The first line contains the length of the sequence NN (2≤N≤50002 \le N \le 5000). The second line contains the NN integers of the sequence, separated by single spaces. Every integer is between 11 and 100000100000 inclusive.

Output

For each test case, print one line in the format Case #x: R, where xx is the test case number starting from 1 and RR is the minimum cost of reducing that sequence to length 1.

Examples1

  1. Example 1

    Input
    10
    6
    15 9 8 13 19 17
    7
    12 15 13 8 12 9 7
    8
    8 12 14 10 14 18 15 13
    9
    12 8 3 1 1 1 5 4 7
    8
    1 6 4 3 2 4 1 6
    8
    15 16 15 10 18 22 19 22
    9
    14 9 14 17 21 23 18 17 14
    8
    13 12 11 5 1 1 6 1
    6
    8 4 2 1 1 1
    8
    9 11 12 8 10 11 6 9
    
    Expected output
    Case #1: 75
    Case #2: 76
    Case #3: 105
    Case #4: 42
    Case #5: 33
    Case #6: 131
    Case #7: 147
    Case #8: 54
    Case #9: 16
    Case #10: 76