Garlands
Time limit2sMemory limit512 MB
Split a weighted sequence of n pieces into m segments of even length, each half-segment at most d pieces, minimizing the maximum half-segment weight.
- Level
Hard8 of 10
- Topics
- Binary search, Dynamic programming, Greedy, Prefix sum
- Solved
- No attempts yet
Problem
Hanging Christmas garlands is a surprisingly demanding job. A garland consists of pieces of equal length. Because of decorations such as Christmas balls, piece has its own weight .
The garland is attached to the ceiling at spots. Its very beginning is attached to spot and its end to spot . It is also hooked to the remaining spots, which splits it into segments, each made of several consecutive pieces. Every decorator must respect the following rules.
- Each segment must contain a positive even number of pieces. Because of this, every segment can be split into two equal half-segments.
- Each half-segment may contain at most pieces.
- The weight of the heaviest half-segment must be minimized. The weight of a half-segment is the sum of the weights of the pieces it contains.
The picture below shows one optimal hanging of a garland with twelve pieces in three segments; the weight of each piece is written inside its circle.

Input
The first line contains a positive integer (), the number of test cases. Then test cases follow.
Each garland is described by two lines. The first line contains three positive integers , , and (, , ), as described above. The second line contains positive integers (), the weights of the pieces.
Output
For each garland, output a single line with one integer: the weight of the heaviest half-segment in an optimal attachment. If it is impossible to hang the garland while satisfying rules 1 and 2, output the word BAD instead.