Bribe the Prisoners (Small)
InterviewTime limit5sMemory limit512 MB
Choose the release order of Q prisoners out of P cells to minimize total bribes, where each release bribes every still-occupied prisoner reachable from it until a boundary or empty cell.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Divide and conquer, Recursion, Intervals
- Solved
- No attempts yet
Problem
A kingdom has prison cells built in a straight line and numbered 1 to . Cell and cell are adjacent, and the prisoners in two adjacent cells are neighbours. A wall with a window separates adjacent cells, so neighbours talk to each other through the window.
Everyone stays calm until a prisoner is released. When that happens, both neighbours of the released prisoner find out, and each of them passes the news to his own other neighbour. That prisoner passes it on again, and the news keeps travelling until it reaches a prisoner who has no further neighbour, either because he is in cell 1, or because he is in cell , or because the next cell is already empty. A prisoner who learns that someone was released smashes everything in his cell unless he is handed one gold coin. So releasing the prisoner in cell forces you to bribe every prisoner on both sides of cell , up to cell 1, up to cell , or up to an empty cell.
Every cell holds exactly one prisoner at the start, and only one prisoner is released per day. Given the prisoners to release over days, find the smallest total number of gold coins you need if you may choose the release order freely.
A bribe works for one day only. A prisoner bribed yesterday must be bribed again if he hears about another release today.
Input
The first line holds the number of test cases . test cases follow. Each case takes two lines. The first line is
P Q
where is the number of prison cells and is the number of prisoners to release. The second line holds distinct cell numbers, space separated, sorted in ascending order.
Limits
- Every cell number is between 1 and , inclusive.
Output
For each test case, print one line in the format
Case #X: C
where is the case number starting from 1, and is the minimum number of gold coins needed for the bribes.
Note
Take , and the cells 3, 6, 14. Releasing cell 14 first, then cell 6, then cell 3 costs . Releasing cell 6 first, then cell 3, then cell 14 costs .