This page is still under construction.

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

Merging Files

Time limit2sMemory limit256 MB

Summary
Compute the cheapest way to merge consecutive chapter files when each merge costs the sum of the two parts.
Level

Medium6 of 10

Topics
Dynamic programming, Intervals, Prefix sum
Solved
No attempts yet

Problem

The novelist Kim Daejeon writes a novel in several chapters and stores each chapter in a separate file. Once every chapter is written, the files are merged into a single file that holds the finished novel. The merging works like this. Two files are merged into one temporary file, and temporary files or original files are again merged two at a time. The two files being merged must hold chapters that run consecutively, and in the end only one file is left. The cost of merging two files is the sum of the two file sizes.

For example, let C1, C2, C3, C4 be files holding four consecutive chapters, with sizes 40, 30, 30, 50. Merging C2 and C3 into a temporary file X1 costs 60. Merging C1 and X1 into X2 then costs 100, and merging X2 with C4 costs 150. The total for that order is 60+100+150=31060+100+150=310. A different order costs less. Merge C1 and C2 into Y1, merge C3 and C4 into Y2, then merge Y1 and Y2, for a total of 70+80+150=30070+80+150=300.

Given the size of the file holding each chapter, write a program that computes the minimum total cost of merging the files into one.

Input

The program reads its input data from standard input. The first line holds the number of test data, TT.

Each test datum is given on two lines. The first line holds a positive integer KK (3≤K≤5003 \le K \le 500), the number of chapters in the novel. The second line holds KK positive integers separated by spaces, the sizes of the files holding chapter 1 through chapter KK. A file size does not exceed 10,000.

Output

The program writes to standard output. For each test datum, print on exactly one line the minimum cost of merging every chapter into a single file.

Examples7

  1. Example 1

    Input
    2
    4
    40 30 30 50
    15
    1 21 3 4 5 35 5 4 3 5 98 21 14 17 32
    
    Expected output
    300
    864
  2. Example 2

    Input
    1
    3
    1 1 1
    
    Expected output
    5
  3. Example 3

    Input
    1
    3
    10000 1 10000
    
    Expected output
    30002
  4. Example 4

    Input
    1
    5
    1 2 3 4 5
    
    Expected output
    33
  5. Example 5

    Input
    1
    6
    100 1 1 1 1 100
    
    Expected output
    316
  6. Example 6

    Input
    3
    3
    5 6 7
    4
    1 1 1 1
    7
    10000 10000 10000 10000 10000 10000 10000
    
    Expected output
    29
    8
    200000
  7. Example 7

    Input
    1
    4
    50 30 30 40
    
    Expected output
    300